Java 8中的java.util.stream.IntStream處理原始int。它有助於解決舊問題,例如以新的方式在數組中找到最大值,在數組中找到最小值,數組中所有元素的總和以及數組中所有值的平均值。 IntStream min()返回描述此流的最小元素的OptionalInt;如果此流為空,則返回一個空的Optional。
用法:
OptionalInt() min() Where, OptionalInt is a container object which may or may not contain a int value.
下麵給出一些示例,以更好地理解該函數。
示例1:
// Java code for IntStream min()
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
IntStream stream = IntStream.of(-9, -18, 54, 8, 7, 14, 3);
// OptionalInt is a container object
// which may or may not contain a
// int value.
OptionalInt obj = stream.min();
// If a value is present, isPresent() will
// return true and getAsInt() will
// return the value
if (obj.isPresent()) {
System.out.println(obj.getAsInt());
}
else {
System.out.println("-1");
}
}
}
輸出:
-18
示例2:
// Java code for IntStream min()
// to get the minimum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// To find minimum in given range
IntStream stream = IntStream.range(50, 75);
// storing the minimum value in variable
// if it is present, else show -1.
int minimum = stream.min().orElse(-1);
// displaying the minimum value
System.out.println(minimum);
}
}
輸出:
50
示例3:
// Java code for IntStream min()
// to get the minimum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// To find minimum in given range
IntStream stream = IntStream.range(50, 50);
// storing the minimum value in variable
// if it is present, else show -1.
int minimum = stream.min().orElse(-1);
// displaying the minimum value
System.out.println(minimum);
}
}
輸出:
-1
相關用法
- Java IntStream max()用法及代碼示例
- Java IntStream toArray()用法及代碼示例
- Java IntStream peek()用法及代碼示例
- Java IntStream distinct()用法及代碼示例
- Java IntStream noneMatch()用法及代碼示例
- Java IntStream empty()用法及代碼示例
- Java IntStream filter()用法及代碼示例
- Java IntStream anyMatch()用法及代碼示例
- Java IntStream count()用法及代碼示例
- Java IntStream allMatch()用法及代碼示例
- Java IntStream average()用法及代碼示例
- Java IntStream.Builder build()用法及代碼示例
- Java IntStream reduce(IntBinaryOperator op)用法及代碼示例
- Java IntStream codePoints()用法及代碼示例
- Java IntStream reduce(int identity, IntBinaryOperator op)用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 IntStream min() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。