Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ordered type of Map from method Collectors.groupingBy

I need to separate list of data into different lists by type, for this purpose I use construction

Map<String,List<Dish>> dishMap = menu.stream()  
         .collect(Collectors.groupingBy(Dish::getType));

but How can I get LinkedHashMap instead HashMap from method "Collectors.groupingBy". I found some data in javadoc but I can`t get what I must to do with this method:

Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy(
                Dish::getType,
                LinkedHashMap::new, ????));

what should I place in the third argument in method "groupingBy" to get what I need?

like image 395
Юрий Яхница Avatar asked Jun 21 '17 11:06

Юрий Яхница


People also ask

What does Collectors groupingBy do?

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.

How to group by using java 8?

In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.

Can we use stream with map in Java?

Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map. values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.

What is collectors in Java?

Java Collectors. Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Java Collectors class provides various methods to deal with elements.


1 Answers

You should use the toList Collector:

Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy(
            Dish::getType,
            LinkedHashMap::new, Collectors.toList()));
like image 147
Flown Avatar answered Oct 17 '22 18:10

Flown