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?
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.
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.
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.
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.
You should use the toList
Collector
:
Map<String,List<Dish>> dishMap = menu.stream().collect(Collectors.groupingBy(
Dish::getType,
LinkedHashMap::new, 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