Collections.max(Collection, Comparator) in Java

Collections.max(Collection, Comparator): This method is available in java.util.Collections class of Java.

Syntax:

<E> E java.util.Collections.max(Collection<? extends E> coll, Comparator<? super E> comp)

This method takes two arguments. This method returns the maximum element of the given collection, according to the order induced by the specified comparator.

Parameters: Two parameters are required for this method.

coll: the collection whose maximum element is to be determined.

comp: the comparator with which to determine the maximum element. A null value indicates that the elements' natural ordering should be used.

Returns: the maximum element of the given collection, according to the specified comparator.

Throws:

1. ClassCastException - if the collection contains elements that are not mutually comparable using the specified comparator.

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 Collectionsmax2 {
    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, null));

    }
}

Output:

67


Approach 2: NoSuchElementException 

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Collectionsmax2 {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();
        System.out.println(Collections.max(arrlist, null));

    }
}

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) at java.base/java.util.Collections.max(Collections.java:710)


No comments:

Post a Comment