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

Юрий Яхница picture Юрий Яхница · Jun 21, 2017 · Viewed 7.5k times · Source

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?

Answer

Flown picture Flown · Jun 21, 2017

You should use the toList Collector:

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