1. Introduction
Finding the minimum element in a List is a frequent requirement in Java. This can be achieved using the Collections.min() method or by utilizing Java 8 streams. This tutorial will guide you on how to find the minimum element in a List employing both techniques.
2. Program Steps
1. Import the necessary libraries.
2. Create a List of integers.
3. Find the minimum element using the Collections.min() method.
4. Find the minimum element using Java 8 stream’s min() method.
5. Output the results.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class FindMinInList {
public static void main(String[] args) {
// Step 2: Create a List of integers
List<Integer> numbers = Arrays.asList(1, 3, 7, 9, 12, 5);
// Step 3: Find the minimum element using the Collections.min() method
Integer minNumberUsingCollections = Collections.min(numbers);
// Step 4: Find the minimum element using Java 8 stream’s min() method
Optional<Integer> minNumberUsingStream = numbers.stream().min(Integer::compare);
// Step 5: Output the results
System.out.println("Minimum number using Collections.min(): " + minNumberUsingCollections);
System.out.println("Minimum number using Stream.min(): " + (minNumberUsingStream.isPresent() ? minNumberUsingStream.get() : "List is empty"));
}
}
Output:
Minimum number using Collections.min(): 1 Minimum number using Stream.min(): 1
4. Step By Step Explanation
Step 1: Import the required classes and interfaces from Java libraries.
Step 2: Instantiate a List of integers with some values.
Step 3: Utilize the Collections.min() method to find the minimum element in the list.
Step 4: Employ the Java 8 stream’s min() method along with Integer::compare to find the minimum element in the list. The min() method returns an Optional, hence it's important to handle the scenario where the List is empty.
Step 5: Display the minimum number determined by both methods to the console.