In this guide, you will learn about the Collections min() method in Java programming and how to use it with an example.
1. Collections min() Method Overview
Definition:
The min() method of the Collections class in Java is used to return the minimum element of the given collection, according to the natural ordering of its elements.
Syntax:
Collections.min(Collection<? extends T> coll)
Parameters:
coll: The collection whose minimum element is to be determined.
Key Points:
- The collection must not be empty, or else a NoSuchElementException will be thrown.
- All elements in the collection must be mutually comparable using the provided comparator (or the natural ordering if using the method without a comparator), otherwise, a ClassCastException is thrown.
- There is an overloaded version of min() that takes a custom comparator as an argument to determine the minimum element based on the comparator's ordering.
2. Collections min() Method Example
import java.util.*;
public class CollectionsMinExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(15, 23, 7, 31, 12));
// Finding the minimum number in the list
int minNumber = Collections.min(numbers);
System.out.println("Minimum number in the list: " + minNumber);
// Finding the minimum string based on length using a custom comparator
List<String> words = new ArrayList<>(Arrays.asList("apple", "banana", "kiwi"));
String shortestWord = Collections.min(words, Comparator.comparingInt(String::length));
System.out.println("Shortest word in the list: " + shortestWord);
}
}
Output:
Minimum number in the list: 7 Shortest word in the list: kiwi
Explanation:
In the provided example, we first create a list of integers and determine the minimum number using the min() method.
Next, we create a list of strings and determine the shortest word by providing a custom comparator to the min() method that compares strings based on their lengths.
Comments
Post a Comment
Leave Comment