Here you can find the source of min(Collection
Parameter | Description |
---|---|
col | Collection of type T |
public static <T extends Comparable<T>> Collection<T> min(Collection<T> col)
//package com.java2s; //License from project: Apache License import java.util.*; public class Main { /**/*from w ww .ja v a2 s . co m*/ * Return a {@link Collection} of all lowest-valued {@code T}. * * <p> * For example a list containing: <pre>[7, 1, 5, 1, 3]</pre> * Will return: <pre>[1, 1]</pre> * * @param col {@link Collection} of type {@code T} * @return {@link Collection} of lowest-valued {@code T} or {@code null} if * {@code col} is {@code null} or empty */ public static <T extends Comparable<T>> Collection<T> min(Collection<T> col) { if (col == null || col.isEmpty()) return null; Collection<T> result = sizedArrayList(col.size()); Iterator<T> it = col.iterator(); T min = it.next(); result.add(min); while (it.hasNext()) { T next = it.next(); int comp = next.compareTo(min); if (comp < 0) { min = next; result = new ArrayList<T>(); result.add(next); } else if (comp == 0) { result.add(next); } } return result; } /** * Return a {@link Collection} of all lowest-valued {@code T}. * * <p> * For example a list containing: <pre>[7, 1, 5, 1, 3]</pre> * Will return: <pre>[1, 1]</pre> * * @param col {@link Collection} of type {@code T} * @param c {@link Comparator} of type {@code T} * @return {@link Collection} of lowest-valued {@code T} or {@code null} if * {@code col} is {@code null} or empty */ public static <T> Collection<T> min(Collection<T> col, Comparator<T> c) { if (col == null || col.isEmpty()) return null; Collection<T> result = sizedArrayList(col.size()); Iterator<T> it = col.iterator(); T min = it.next(); result.add(min); while (it.hasNext()) { T next = it.next(); int comp = c.compare(next, min); if (comp < 0) { min = next; result = new ArrayList<T>(); result.add(next); } else if (comp == 0) { result.add(next); } } return result; } /** * Returns a sized array list of type {@code T}. * * @param <T> Formal type parameter * @param size Array list size * @return Array list of type {@code T} */ public static <T> ArrayList<T> sizedArrayList(final int size) { return new ArrayList<T>(size); } }