📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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