A Map
is a mapping from keys to values. You need to define, for each element of the list, what should be the key, and what should be the value.
Your original code:
for(int i=0;i<list.size();i++) {
HashMap hMap=new HashMap();
hMap.put("Data", list);
}
This effectively maps the key "Data" to the value list
, repeating this mapping several times, but you only have entry.
Here's an example of taking a List<String>
, and constructing a map from a letter to a string starting from that letter from the list.
List<String> list = Arrays.asList(
"abc", "def", "ghi", "ijk", "abracadabra"
);
Map<Character,String> map = new HashMap<Character,String>();
for (String s : list) {
map.put(s.charAt(0), s);
}
System.out.println(map); // prints "{g=ghi, d=def, a=abracadabra, i=ijk}"
System.out.println(map.get('i')); // prints "ijk"
System.out.println(map.containsKey('x')); // prints "false"
Note that "abc"
is "lost" in the map. That's because you can only map one key to one value. On the other hand, you can have a Map<Character,Set<String>>
, that is a map from each key to a set of values. This is effectively what a multimap is, and Guava has an implementation.
Related questions