Collections.min(Collection, Comparator) in Java

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

Syntax:

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

This method takes two arguments. This method returns the minimum 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 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:

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 Collectionsmin2 {
    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.min(arrlist, null));

    }
}

Output:

2


Approach 2: NoSuchElementException 

Java

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

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

        List<Integer> arrlist = new ArrayList<Integer>();

        System.out.println(Collections.min(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.min(Collections.java:601) at java.base/java.util.Collections.min(Collections.java:637)


No comments:

Post a Comment