diff --git a/src/java/com/samskivert/util/CollectionUtil.java b/src/java/com/samskivert/util/CollectionUtil.java index 95042dad..070885b2 100644 --- a/src/java/com/samskivert/util/CollectionUtil.java +++ b/src/java/com/samskivert/util/CollectionUtil.java @@ -24,6 +24,7 @@ import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; +import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; @@ -102,6 +103,65 @@ public class CollectionUtil } } + /** + * Return a List containing all the elements of the specified Iterable that compare as being + * equal to the maximum element. + * + * @throws NoSuchElementException if the Iterable is empty. + */ + public static > List maxList (Iterable iterable) + { + return maxList(iterable, Comparators.comparable()); + } + + /** + * Return a List containing all the elements of the specified Iterable that compare as being + * equal to the maximum element. + * + * @throws NoSuchElementException if the Iterable is empty. + */ + public static List maxList (Iterable iterable, Comparator comp) + { + Iterator itr = iterable.iterator(); + T max = itr.next(); + List maxes = new ArrayList(); + maxes.add(max); + while (itr.hasNext()) { + T elem = itr.next(); + int cmp = comp.compare(max, elem); + if (cmp <= 0) { + if (cmp < 0) { + max = elem; + maxes.clear(); + } + maxes.add(elem); + } + } + return maxes; + } + + /** + * Return a List containing all the elements of the specified Iterable that compare as being + * equal to the minimum element. + * + * @throws NoSuchElementException if the Iterable is empty. + */ + public static > List minList (Iterable iterable) + { + return maxList(iterable, java.util.Collections.reverseOrder()); + } + + /** + * Return a List containing all the elements of the specified Iterable that compare as being + * equal to the minimum element. + * + * @throws NoSuchElementException if the Iterable is empty. + */ + public static List minList (Iterable iterable, Comparator comp) + { + return maxList(iterable, java.util.Collections.reverseOrder(comp)); + } + /** * Returns a list containing a random selection of elements from the * specified collection. The total number of elements selected will be