如何从番石榴列表中获取max()元素 [英] How to get max() element from List in Guava
本文介绍了如何从番石榴列表中获取max()元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我们有一套物品:
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?
推荐答案
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);
效率最高:遍历列表中的项目,并返回价格最高的第一个项目:O(n).
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).
这篇关于如何从番石榴列表中获取max()元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文