Collections.max(Collection): This method is available in java.util.Collections class of Java.
Syntax:
<E> E java.util.Collections.max(Collection<? extends E> coll)
This method takes one argument. This method returns the maximum element of the given collection, according to the natural ordering of its elements.
Parameters: One parameter is required for this method.
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:
1. ClassCastException - if the collection contains elements that are not mutually comparable.
2. NoSuchElementException - if the collection is empty.
Approach 1: When no exception
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Collectionsmax {public static void main(String[] args) {List<Integer> arrlist = new ArrayList<Integer>();arrlist.add(12);arrlist.add(32);arrlist.add(67);arrlist.add(2);System.out.println(Collections.max(arrlist));}}
Output:
67
Approach 2: NoSuchElementException
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Collectionsmax {public static void main(String[] args) {List<Integer> arrlist = new ArrayList<Integer>();System.out.println(Collections.max(arrlist));}}
Output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970) at java.base/java.util.Collections.max(Collections.java:674)
No comments:
Post a Comment