1. Introduction
Finding the minimum element in a Set in Java is a common task that can be done efficiently using Java Streams. Streams provide a straightforward and readable way to perform operations on collections. In this guide, we will learn how to find the minimum element in a Set using Java.
2. Program Steps
1. Import the necessary libraries.
2. Create and initialize a Set of integers.
3. Utilize the stream’s min() method to find the minimum element in the set.
4. Output the result.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
public class FindMinInSet {
public static void main(String[] args) {
// Step 2: Create and initialize a Set of integers
Set<Integer> numbersSet = new HashSet<>(Set.of(4, 15, 6, 23, 17));
// Step 3: Utilize the stream’s min() method to find the minimum element in the set
Optional<Integer> minNumber = numbersSet.stream().min(Integer::compareTo);
// Step 4: Output the result
System.out.println("Minimum number in the set is: " + (minNumber.isPresent() ? minNumber.get() : "Set is empty"));
}
}
Output:
Minimum number in the set is: 4
4. Step By Step Explanation
Step 1: Start by importing the required libraries. For this program, we need Set, HashSet, and Optional.
Step 2: Initialize a Set of integers containing some values.
Step 3: To find the minimum element in the Set, use the min() method of the stream API along with Integer::compareTo. The min() method returns an Optional, and it is necessary to handle cases where the Set might be empty.
Step 4: Print out the minimum number found in the Set.