Collection max/min value
In this chapter you will learn:
Get the max and min value from a Collection
Collections
class has helper methods to return the max and min value
for a collection. A collection may be an ArrayList
, a
LinkedList
or a HashSet
.
static<T extends Object & Comparable<? super T>>T max(Collection<? extends T> coll)
Returns the maximum element according to the natural ordering.static<T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
Returns the maximum element according to the order induced by the specified comparator.static<T extends Object & Comparable<? super T>>T min(Collection<? extends T> coll)
Returns the minimum element according to the natural ordering of its elements.static<T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
Returns the minimum element according to the order induced by the specified comparator.
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
//from jav a 2s. com
public class Main {
public static void main(String args[]) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(-8);
list.add(20);
list.add(-20);
list.add(8);
Comparator<Integer> r = Collections.reverseOrder();
Collections.sort(list, r);
System.out.print("List sorted in reverse: ");
System.out.print(list);
System.out.println();
Collections.shuffle(list);
System.out.print("List shuffled: ");
System.out.print(list);
System.out.println();
System.out.println("Minimum: " + Collections.min(list));
System.out.println("Maximum: " + Collections.max(list));
}
}
The output:
Next chapter...
What you will learn in the next chapter: