Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; public class Main { /** * 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 <T extends Comparable<? super T>> List<T> minList(Iterable<T> 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 <T> List<T> minList(Iterable<T> iterable, Comparator<? super T> comp) { return maxList(iterable, java.util.Collections.reverseOrder(comp)); } /** * 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 <T extends Comparable<? super T>> List<T> maxList(Iterable<T> iterable) { return maxList(iterable, new Comparator<T>() { public int compare(T o1, T o2) { return o1.compareTo(o2); } }); } /** * 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 <T> List<T> maxList(Iterable<T> iterable, Comparator<? super T> comp) { Iterator<T> itr = iterable.iterator(); T max = itr.next(); List<T> maxes = new ArrayList<T>(); maxes.add(max); if (itr.hasNext()) { do { T elem = itr.next(); int cmp = comp.compare(max, elem); if (cmp <= 0) { if (cmp < 0) { max = elem; maxes.clear(); } maxes.add(elem); } } while (itr.hasNext()); } else if (0 != comp.compare(max, max)) { // The main point of this test is to compare the sole element to something, // in case it turns out to be incompatible with the Comparator for some reason. // In that case, we don't even get to this IAE, we've probably already bombed out // with an NPE or CCE. For example, the Comparable version could be called with // a sole element of null. (Collections.max() gets this wrong.) throw new IllegalArgumentException(); } return maxes; } }