👑 To find the maximum number in a Set
using Java Streams, you can use the max()
terminal method with a comparator.
✅ Example: Find Max in a Set
import java.util.Set;
import java.util.Comparator;
public class MaxInSet {
public static void main(String[] args) {
Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);
numbers.stream()
.max(Comparator.naturalOrder()) // or just Comparator.comparingInt(i -> i)
.ifPresent(max -> System.out.println("Max: " + max));
}
}
🔹 Output:
Max: 40
✅ Explanation:
.stream()
– converts theSet
to a stream.max(...)
– finds the max using natural order.ifPresent(...)
– safely prints the result (sincemax()
returns anOptional<T>
)
🧠 Bonus: Use Collections.max()
(alternative way)
int max = Collections.max(numbers);
System.out.println("Max: " + max);