Collections static > T max(Collection coll) method Example Program


Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(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
 *              Collections.max(Collection<? extends T> coll)
 */

public class Max {
	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("Max value is: " + Collections.max(list));
	}
}

Output

Max value is: 87

Explanation

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(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 maximum element is to be determined.
Returns:
the maximum element of the given collection, according to the natural ordering of its elements.
Throws:
ClassCastException - if the collection contains elements that are not mutually comparable (for example, strings and integers).
NoSuchElementException - if the collection is empty.
See Also:
Comparable


Related Post

Comments


©candidjava.com