For my example, having car object and found that min and max price value based on model (group by).
List carsDetails = UserDB.getCarsDetails();
Ma
Here is a very concise solution. It collects all Car
s into a SortedSet
and thus works without any additional classes.
Map> grouped = carDetails.stream()
.collect(groupingBy(Car::getMake, toCollection(
() -> new TreeSet<>(comparingDouble(Car::getPrice)))));
grouped.forEach((make, cars) -> System.out.println(make
+ " cheapest: " + cars.first()
+ " most expensive: " + cars.last()));
A possible downside is performance, as all Car
s are collected, not just the current min and max. But unless the data set is very large, I don't think it will be noticeable.