How to get max() element from List in Guava

后端 未结 3 1228
我在风中等你
我在风中等你 2020-12-05 06:33

Let\'s say we have a Collection of Items:

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

List list = getListOfItems();

相关标签:
3条回答
  • 2020-12-05 07:10
    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).

    0 讨论(0)
  • 2020-12-05 07:22

    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.)

    0 讨论(0)
  • 2020-12-05 07:24

    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.

    0 讨论(0)
提交回复
热议问题