Java中IntStream min()方法
Java IntStream 類中的 IntStream min() 方法用於從流中獲取最小元素。它返回一個描述此流的最小元素的 OptionalInt,或如果此流為空,則返回一個空可選項。
語法如下
OptionalInt min()
其中,OptionalInt 是一個容器物件,可能包含 int 值,也可能不包含。
建立 IntStream 並新增一些元素
IntStream intStream = IntStream.of(89, 45, 67, 12, 78, 99, 100);
現在,獲取流的最小元素
OptionalInt res = intStream.min();
以下是 Java 中實現 IntStream min() 方法的一個示例。OptionalInt 類的 isPresent() 方法在存在值時返回 true
示例
import java.util.*; import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.of(89, 45, 67, 12, 78, 99, 100); OptionalInt res = intStream.min(); System.out.println("The minimum element of this stream:"); if (res.isPresent()) { System.out.println(res.getAsInt()); } else { System.out.println("Nothing!"); } } }
輸出
The minimum element of this stream: 12
廣告