To find the minimum number in a Set
, you can use the min()
method in a stream — just like you did with max()
.
✅ Example: Find Min in a Set
import java.util.Set;
import java.util.Comparator;
public class MinInSet {
public static void main(String[] args) {
Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);
numbers.stream()
.min(Comparator.naturalOrder())
.ifPresent(min -> System.out.println("Min: " + min));
}
}
🔹 Output:
Min: 7
✅ Explanation
Method | Purpose |
---|---|
.stream() | Turns the set into a stream |
.min(...) | Finds the minimum value |
Comparator.naturalOrder() | Compares using natural ordering |
.ifPresent(...) | Handles the Optional result safely |