Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream groupingby

Tags:

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>>?

like image 346
Omer Avatar asked Jan 15 '15 17:01

Omer


People also ask

What is groupingBy java8?

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.

How does collectors groupingBy work?

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.

What is stream () in Java?

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.

What is Java Util stream collectors?

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.


1 Answers

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()))); 
like image 191
Eran Avatar answered Dec 03 '22 08:12

Eran