Search code examples
javalistcollectionsjava-streamcompare

Compare two lists based on highest value and subsequent values?


I have two lists of:

List<Person> persons;

each Person has the attribute - score

e.g.

list1:

person.score = 3
person.score = 5
person.score = 8

list2:

person.score = 8
person.score = 4
person.score = 7

I want to compare each list to find the highest score in each. If both highest are the same, then I want to compare the second highest etc and so on.

How can I do so?


Solution

  • You can make a copy of each List, sort these copies, then compare them element by element.

    Comparator<List<Person>> comp = (a, b) -> {
        List<Person> s1 = a.stream().sorted(Comparator.comparingInt(Person::getScore).reversed()).toList(), 
                     s2 = b.stream().sorted(Comparator.comparingInt(Person::getScore).reversed()).toList();
        for (int i = 0; i < Math.min(a.size(), b.size()); i++) {
            int c = Integer.compare(s1.get(i).getScore(), s2.get(i).getScore());
            if (c != 0) return c;
        }
        return Integer.compare(a.size(), b.size());
    };