Collections.min(Collection) in Java

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

Syntax:

<E> E java.util.Collections.min(Collection<? extends E> coll)

This method takes one argument. This method returns the minimum 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 minimum element is to be determined.

Returns: the minimum 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 Collectionsmin {
    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));

    }
}

Output:

2


Approach 2: NoSuchElementException

Java

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

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

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

        System.out.println(Collections.min(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.min(Collections.java:601)


No comments:

Post a Comment