From ae67d873e8b5cc2144adb910ac9787bb6856dc28 Mon Sep 17 00:00:00 2001 From: "ray.j.greenwell" Date: Thu, 15 Apr 2010 23:57:05 +0000 Subject: [PATCH] Added maxList() and minList(). git-svn-id: https://samskivert.googlecode.com/svn/trunk@2772 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../com/samskivert/util/CollectionUtil.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) 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