How to get all elements with the highest value with Java streams?

Viewed 477

I have the following pojo:

class MyPojo {
    String name;
    int priority;
}

I have a List<MyPojo>. Now, I want to retrieve all elements which have the highest priority. The order of those elements does not matter.

Is this possible with Java streams? I think I should first group by priority and then get all elements belonging to the highest priority, but I am not sure how to do this in an efficient manner.

2 Answers

You should cast it to IntStream and get the max() out of it. And then get every pojos with this value.

import java.util.List;
import java.util.stream.Collectors;

class MyPojo {
    String name;
    int priority;

    public int getPriority() {
        return priority;
    }
}

public class Main {
    public static void main(String[] args) {
        List<MyPojo> list = null;
        int max = list.stream().mapToInt(MyPojo::getPriority).max().orElse(Integer.MIN_VALUE);
        List<MyPojo> maxPojos = list.stream().filter(pojo -> pojo.getPriority() == max).collect(Collectors.toList());
    }
}

You can do this using a TreeMap and the Collectors.groupingBy():

TreeMap<Integer, List<MyPojo>> map = pojos.stream()
                                          .collect(Collectors.groupingBy(
                                              MyPojo::getPriority, 
                                              TreeMap::new, 
                                              Collectors.toList()
                                           ));

List<MyPojo> maxPrios = map.lastEntry().getValue();

The lastEntry() will return the pojos with the highest priority, due to the natural ordering of Integers where the smallest value will be first, and the largest value will be last.

Related