I have a list of maps.
List
The values in the list are, for example
<1, String1>
&l
Have a look at guavas MultiMap. Should be exactly what you are looking for:
http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap
You can do it the following with Java 8:
private void init() {
List<Map<Integer, String>> mapList = new ArrayList<>();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "String1");
mapList.add(map1);
Map<Integer, String> map2 = new HashMap<>();
map2.put(2, "String2");
mapList.add(map2);
Map<Integer, String> map3 = new HashMap<>();
map3.put(1, "String3");
mapList.add(map3);
Map<Integer, String> map4 = new HashMap<>();
map4.put(2, "String4");
mapList.add(map4);
Map<Integer, List<String>> response = mapList.stream()
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(
Map.Entry::getValue,
Collectors.toList()
)
)
);
response.forEach((i, l) -> {
System.out.println("Integer: " + i + " / List: " + l);
});
}
This will print:
Integer: 1 / List: [String1, String3]
Integer: 2 / List: [String2, String4]
Explanation (heavily warranted), I am afraid I cannot explain every single detail, you need to understand the basics of the Stream
and Collectors
API introduced in Java 8 first:
Stream<Map<Integer, String>>
from the mapList
.flatMap
operator, which roughly maps a stream into an already existing stream.Map<Integer, String>
to Stream<Map.Entry<Integer, String>>
and add them to the existing stream, thus now it is also of type Stream<Map.Entry<Integer, String>>
.Stream<Map.Entry<Integer, String>>
into a Map<Integer, List<String>>
.Collectors.groupingBy
, which produces a Map<K, List<V>>
based on a grouping function, a Function
that maps the Map.Entry<Integer, String>
to an Integer
in this case.Map.Entry::getKey
, it operates on a Map.Entry
and returns an Integer
.Map<Integer, List<Map.Entry<Integer, String>>>
if I had not done any extra processing.Collectors.groupingBy
, which has to provide a collector.Map.Entry
entries to their String
values via the reference Map.Entry::getValue
.Collectors.toList()
here, as I want to add them to a list.Map<Integer, List,String>>
.