Finds the maximum element in the collection - Android java.util

Android examples for java.util:Collection Find

Description

Finds the maximum element in the collection

Demo Code


//package com.book2s;

import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(getMax(c));
    }/*w  ww. j  a va 2 s .co m*/

    /**
     * Finds the maximum element in the collection
     * @param c the collection we are searching in
     * @return the max element in collection c 
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <G> G getMax(Collection<G> c) {
        if (c.isEmpty() == true) {
            throw new UnsupportedOperationException(
                    "Can't find max in empty collection");
        }
        Iterator<G> itr = c.iterator();
        G max = itr.next();
        while (itr.hasNext()) {
            G current = itr.next();
            if (((Comparable) max).compareTo((Comparable) current) < 0) {
                max = current;
            }
        }
        return max;
    }
}

Related Tutorials