Java.Java8.How can I find the maximum number in a set?

👑 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 the Set to a stream
  • .max(...) – finds the max using natural order
  • .ifPresent(...) – safely prints the result (since max() returns an Optional<T>)

🧠 Bonus: Use Collections.max() (alternative way)

int max = Collections.max(numbers);
System.out.println("Max: " + max);
This entry was posted in Без рубрики. Bookmark the permalink.