Filtering Java Streams of Nested Collections with Min / Max
I have Map<Integer, List<MyDayObject>>
one that represents all days by week of the year.
Now I only need to analyze the days that gave the maximum value for each week. I was able to get nested streaming with help forEach
, but I can't seem to pipe it right collect
to the end 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);
});
I need, however, not print, but get List<MyDayObject> allHighest
at the end.
I've tried .filter
from .entrySet()
to .max()
but can't get this to work.
What is the best way to filter Map
on max
nested List
?
source to share
You seem to 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 might be possible. I focused on getting the desired result.
As holi-java commented, a lambda expression that compares elements can be simplified:
List<MyDayObject> allHighest =
weeks.values()
.stream()
.map(list -> list.stream().max(Comparator.comparing(MyDayObject::value)).get())
.collect(Collectors.toList());
source to share