Collection static T min(Collection coll, Comparator comp) method Example Program


Returns the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).

Program

package com.candidjava;

import java.util.*;

/**
 * 
 * @author karthikeyan.T
 * @description The following example shows the usage of
 *              Collectionsmin(Collection<? extends T> coll, Comparator<? super
 *              T> comp)
 */

public class MinReverse {
	public static void main(String args[]) {
		LinkedList list = new LinkedList();
		list.add(34);
		list.add(-450);
		list.add(-245);
		list.add(87);
		System.out.println("Min value is: " + Collections.min(list));
		System.out.println("Min val: "
				+ Collections.min(list, Collections.reverseOrder()));
	}
}

Output

Min value is: -450
Min val: 87

Explanation

public static <T> T min(Collection<? extends T> coll,Comparator<? super T> comp)
Returns the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.

Parameters:
coll - the collection whose minimum element is to be determined.
comp - the comparator with which to determine the minimum element. A null value indicates that the elements' natural ordering should be used.
Returns:
the minimum element of the given collection, according to the specified comparator.
Throws:
ClassCastException - if the collection contains elements that are not mutually comparable using the specified comparator.
NoSuchElementException - if the collection is empty.
See Also:
Comparable


Related Post

Comments


©candidjava.com