How to get max() element from List in Guava

2020-01-30 08:08发布

问题:

Let's say we have a Collection of Items:

class Item {
    public String title;
    public int price;
}

List<Item> list = getListOfItems();

I would like to get an Item with a maximum price out of that list with Guava library (with Ordering, I presume). I mean something similar to this Groovy code:

list.max{it.price}

How do I do that? How efficient is it?

回答1:

Ordering<Item> o = new Ordering<Item>() {
    @Override
    public int compare(Item left, Item right) {
        return Ints.compare(left.price, right.price);
    }
};
return o.max(list);

It's as efficient as it can be: it iterates through the items of the list, and returns the first of the Items having the maximum price: O(n).



回答2:

According to JB's answer, you can also use some shorthand when working with values which have natural order, for example:

Ordering.<Integer> natural().max(listOfIntegers);

See Ordering.natural() for details.



回答3:

You can do this without Guava.

Collections provides min and max methods that operate on any Collection, including overloads taking comparators. Here we use the Java 8 Comparator static methods with a lambda to concisely specify a comparator, but before Java 8 you can use an anonymous class:

Item max = Collections.max(list, Comparator.comparingInt(i -> i.price));

These methods will throw NoSuchElementException if the collection is empty.


Java 8 streams provide min and max functions taking a comparator. These functions return Optional<T> to gracefully handle the stream being empty. The static methods in Comparator are useful for concisely specifying comparators, including the common case of the natural ordering. For this question, you'd use

Optional<Item> max = list.stream().max(Comparator.comparingInt(i -> i.price));

This will work for any stream source, which includes all Collection implementations, as well as other things like files, and makes it easy to compute the max of a subset of a collection by filtering the stream. If you have a large collection and an expensive comparator (e.g., String's natural ordering), you can use a parallel stream.

(Aside: ideally Stream would provide min and max overloads taking no argument when the stream type implements Comparable. Unfortunately Java doesn't support conditionally exposing methods based on a type parameter, and it isn't worth introducing a new StreamOfComparable interface extending Stream just for this case.)



标签: java guava