How to get max() element from List in Guava

后端 未结 3 1230
我在风中等你
我在风中等你 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条回答
  •  萌比男神i
    2020-12-05 07:10

    Ordering o = new Ordering() {
        @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).

提交回复
热议问题