Java List Max maxList(Iterable iterable)

Here you can find the source of maxList(Iterable iterable)

Description

Return a List containing all the elements of the specified Iterable that compare as being equal to the maximum element.

License

Open Source License

Exception

Parameter Description
NoSuchElementException if the Iterable is empty.

Declaration

public static <T extends Comparable<? super T>> List<T> maxList(Iterable<T> iterable) 

Method Source Code


//package com.java2s;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Iterator;
import java.util.List;

public class Main {
    /**//from   w w w  .j a va  2 s.  c o m
     * 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;
    }
}

Related

  1. maxInnerSize(List> listOfLists)
  2. maxInt(List array)
  3. maxLength(List patterns)
  4. maxLength(List list)
  5. maxLength(List strings)
  6. maxStringLength(List strings)