📜  java int stream min - Java (1)

📅  最后修改于: 2023-12-03 15:01:30.470000             🧑  作者: Mango

Java IntStream Min

In Java, IntStream is a specialized stream that deals with primitive int values. One of the handy methods available in IntStream is min(), which returns the smallest element in the stream.

Here's an example that uses IntStream to find the smallest element in an array of integers:

int[] nums = {33, 12, 45, 65, 23, 8};

int min = IntStream.of(nums)
                   .min()
                   .orElseThrow(IllegalStateException::new);

System.out.println("The smallest number is: " + min);

In this example, we create an IntStream from the nums array using the of method. We then call min() on the stream, which returns an OptionalInt containing the smallest element. If the stream is empty, we throw an IllegalStateException. Finally, we print out the smallest number using System.out.println.

It's worth noting that min() doesn't modify the stream in any way. It simply returns the smallest element. If you need to get the smallest n elements or modify the stream in any other way, you'll need to use other methods.

int[] nums = {33, 12, 45, 65, 23, 8};

IntStream.of(nums)
         .sorted()
         .limit(3)
         .forEach(System.out::println);

In this example, we sort the IntStream using the sorted() method, then use limit(3) to take the first three elements, and finally use forEach to print out each element.

In conclusion, if you need to find the smallest integer in a stream of integers, the IntStream min() method is a quick and easy way to do it.