Java 8中的java.util.stream.IntStream处理原始int。它以新的方式帮助解决诸如在数组中找到最大值,在数组中找到最小值,数组中所有元素的总和以及数组中所有值的平均值之类的问题。 IntStream max()返回描述此流的最大元素的OptionalInt;如果此流为空,则返回一个空的Optional。
用法:
OptionalInt() max() Where, OptionalInt is a container object which may or may not contain a int value.
示例1:
// Java code for IntStream max()
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.max();
// 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");
}
}
}
输出:
54
示例2:
// Java code for IntStream max()
// to get the maximum 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 maximum in given range
IntStream stream = IntStream.range(50, 75);
// storing the maximum value in variable
// if it is present, else show -1.
int maximum = stream.max().orElse(-1);
// displaying the maximum value
System.out.println(maximum);
}
}
输出:
74
示例3:
// Java code for IntStream max()
// to get the maximum 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 maximum in given range
IntStream stream = IntStream.range(50, 50);
// storing the maximum value in variable
// if it is present, else show -1.
int maximum = stream.max().orElse(-1);
// displaying the maximum value
System.out.println(maximum);
}
}
输出:
-1
相关用法
- Java IntStream min()用法及代码示例
- 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 max() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。