I have List<Map<String, String>>
each item in the list is a map e.g
companyName - IBM firstName - James country - USA ...
I would like create a Map<String, List<String>>
where it maps companyName to a list of of firstName e.g
IBM -> James, Mark ATT -> Henry, Robert.. private Map<String,List<String>> groupByCompanyName(List<Map<String, String>> list) { return list.stream().collect(Collectors.groupingBy(item->item.get("companyName"))); }
but this will create Map<String, List<Map<String, String>>
(mapping comanyName to a list of maps)
how to create a Map<String, List<String>>
?
groupingBy() method in Java 8 now permits developers to perform GROUP BY operation directly. GROUP BY is a SQL aggregate operation that is quite useful. It enables you to categorise records based on specified criteria.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL's GROUP BY clause.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
java.util.stream.Collectors. Implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.
Haven't tested it, but something like this should work:
Map<String, List<String>> namesByCompany = list.stream() .collect(Collectors.groupingBy(item->item.get("companyName"), Collectors.mapping(item->item.get("firstName"), Collectors.toList())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With