MultiValueMap in java
87,843
Solution 1
You can try following :
String a, b, c;
MultiMap mMap = new MultiValueMap();
mMap.put("a", "Hello there, It's a wonderful day");
mMap.put("a", "nice to meet you");
Set<String> keys = mMap.keySet();
for (String key : keys) {
System.out.println("Key = " + key);
System.out.println("Values = " + mMap.get(key));
List<String> list = (List<String>) mMap.get(key);
b = list.get(0);
c = list.get(1);
System.out.println("B : " + b);
System.out.println("C : " + c);
}
Solution 2
You don't have to do a split. This is the documentation of MultiMap that is found:
MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);
Now when you do a get()
call on a multimap, it gives you a collection. The first item will be your b and the second one will be your c.
Solution 3
You can also use a key and object to store multiple values in Multimap. Something like this, MultiValueMap mv = new LinkedMultiValueMap<~>();
Author by
user3810857
Updated on October 23, 2022Comments
-
user3810857 over 1 year
I'm studying with Hashmap with Multiple parameters(1 key, 2 values) and i was able to find apache multiValueMap for my issue.
Here is my codes for multiValueMap.
import java.util.Set; import org.apache.commons.collections.map.MultiValueMap; import org.apache.commons.collections.MultiMap; public class multiValueMap { public static void main(String args[]) { String a, b, c; MultiMap mMap = new MultiValueMap(); mMap.put("a", "Hello there, It's a wonderful day"); mMap.put("a", "nice to meet you"); Set<String> keys = mMap.keySet(); for (String key : keys) { System.out.println("Key = " + key); System.out.println("Values = " + mMap.get(key)); a = String.valueOf(mMap.get(key)); System.out.println("A : " + a); } } } // The result as below Key = a Value = [Hello there, It's a wonderful day, nice to meet you] A : [Hello there, It's a wonderful day, nice to meet you]
Here is my question how can I store first value for string b, and second for c? if I substring the MultiMap values depends on "," then it would stores Hello there only. please give me helpful your advices.
-
user3810857 about 9 yearsSeems like it needs more details. actually, I want to store numerous data(more than 1000) from DB and it covers 3 parameters(data no(int), channel id(int), description(String)). but If I store them to Hashmap(Key, Value) It's not enough for 3 paramets hence, I decided to use MultiValueMap. 2 answers above does not fully solve my issue.