Create Map<String, List<Object>> where the elements of the lists are sorted, using Stream API

Viewed 74

I have any ArrayList of "Monitor" objects. Each object has two fields, "brand::String", and "price::BigDecimal". I am using the following Stream, to taxinomize the Monitor objects into a HashMap<String, List<Monitor>>, where key is the name (so monitors with the same name end up in the same list:

Map<String, List<Monitor>> monitorsByNameMap =
    monitors.stream()
        .collect(Collectors.groupingBy(Monitor::getName));

I would like each List<Monitor> in the HashMap to be sorted based on the price of each Monitor object - preferably in ascending order. I was wondering if that can be achieved by adding to the above expression.

1 Answers

You can use collectingAndThen after grouping by name

Map<String, List<Monitor>> monitorsByNameMap = monitors.stream()
                  .collect(Collectors.groupingBy(Monitor::getName,
                        Collectors.collectingAndThen(Collectors.toList(),
                              l -> l.stream()
                                       .sorted(Comparator.comparing(Monitor::getPrice))
                                       .collect(Collectors.toList())
                            ))
                    );
Related