Java Streams – How to group by value and find min and max value of each group?

前端 未结 3 2046
情话喂你
情话喂你 2020-12-05 20:26

For my example, having car object and found that min and max price value based on model (group by).

List carsDetails = UserDB.getCarsDetails();
Ma         


        
3条回答
  •  遥遥无期
    2020-12-05 21:14

    Here is a very concise solution. It collects all Cars 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 Cars 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.

提交回复
热议问题