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