[英]Finding minimum value according to a comparator
I was wondering if there is a way to find the minimum or maximum of a collection using a comparator in the Apache commons-collection library. 我想知道是否有一种方法可以使用Apache commons-collection库中的比较器查找集合的最小值或最大值。 Something equivalent to this using Guava:
使用Guava与此等效:
return Ordering.from(comparator).max(collection);
java.util.Collections
has methods java.util.Collections
具有方法
max(Collection) // natural order
max(Collection, Comparator) // according to compare provided
min(Collection) // natural order
min(Collection, Comparator) // according to compare provided
like so: 像这样:
Item getMax(Collection<Item> items, Comparator<Item> comparator) {
Item temp = null;
for(Item item : items) {
if(temp == null || comparator.compare(temp, item) < 0)
temp = item;
}
return temp;
}
Item getMin(Collection<Item> items, Comparator<Item> comparator) {
Item temp = null;
for(Item item : items) {
if(temp == null || comparator.compare(temp, item) > 0)
temp = item;
}
return temp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.