Returns the first minimum value of the given collection. - Java java.util

Java examples for java.util:Collection First Element

Description

Returns the first minimum value of the given collection.

Demo Code


//package com.book2s;

import java.util.Collection;

import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection vals = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(getMin(vals));
    }/*  w w  w. j a  v a2s.  c o  m*/

    /**
     * Returns the first minimum value of the given collection.
     * If the collection is empty, null is returned.
     */
    public static <T extends Comparable<T>> T getMin(Collection<T> vals) {
        return getExtremum(vals, -1);
    }

    private static <T extends Comparable<T>> T getExtremum(
            Collection<T> vals, int comparator) {
        if (vals.size() == 0)
            return null;
        Iterator<T> it = vals.iterator();
        T ret = it.next();
        while (it.hasNext()) {
            T v = it.next();
            if (v.compareTo(ret) * comparator > 0)
                ret = v;
        }
        return ret;
    }
}

Related Tutorials