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

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

MethodPurpose
.stream()Turns the set into a stream
.min(...)Finds the minimum value
Comparator.naturalOrder()Compares using natural ordering
.ifPresent(...)Handles the Optional result safely
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.