简体   繁体   中英

Java Streams Filtering Nested Collections by Min/Max

I have a Map<Integer, List<MyDayObject>> that represents all days by week of year.
Now I need to analyze only the days that produced the highest value for each week. I have been able to get the nested streaming working with a forEach but I can't seem to be able to correctly stream it and collect into a List at the end.

weeks.forEach((k, v) -> { 
        MyDayObject highest = v.stream()
            .max((o1, o2) -> o1.value().compareTo(o2.value())).get();      
        System.out.println(highest);
    });

What I need though is not to print it but get a List<MyDayObject> allHighest at the end.

I tried .filter ing the .entrySet() by .max() but can't get that to work.
What's the best way to filter a Map by max of the nested List ?

It appears you need to map each value of the original Map to the corresponding max MyDayObject :

List<MyDayObject> allHighest = 
    weeks.values() // produces a Collection<List<MyDayObject>>
         .stream() // produces a Stream<List<MyDayObject>>
         .map(list -> list.stream() // transforms each List<MyDayObject> to a MyDayObject 
                                    // to obtain a Stream<MyDayObject>
                          .max((o1, o2) -> o1.value().compareTo(o2.value())).get())
         .collect(Collectors.toList()); // collects the elements to a List

PS I just copied your code that finds the maximum element of a given list without trying to improve it, which may be possible. I focused on getting the desired output.

As holi-java commented, the lambda expression that compares the elements can be simplified:

List<MyDayObject> allHighest = 
    weeks.values() 
         .stream() 
         .map(list -> list.stream().max(Comparator.comparing(MyDayObject::value)).get())
         .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM