简体   繁体   English

根据比较器求最小值

[英]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

Why not simply use the min and max methods of the Collection class? 为什么不简单地使用Collection类的minmax方法呢?

Example: 例:

  LinkedList<Integer> list = new LinkedList<Integer>();
  list.add(-15);  
  list.add(33);  
  list.add(-23);  
  list.add(11); 
  System.out.println("Max value: " + Collections.max(list,comparator)); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM