Java 8中的java.util.stream.LongStream处理原始的long。它以新的方式帮助解决诸如在数组中找到最大值,在数组中找到最小值,数组中所有元素的总和以及数组中所有值的平均值之类的问题。 LongStream max()返回描述此流的最大元素的OptionalLong;如果此流为空,则返回一个空的Optional。
用法:
OptionalLong() max() Where, OptionalLong is a container object which may or may not contain a long value.
示例1:
// Java code for LongStream max()
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(-9L, -18L, 54L,
8L, 7L, 14L, 3L);
// OptionalLong is a container object
// which may or may not contain a
// long value.
OptionalLong obj = stream.max();
// If a value is present, isPresent() will
// return true and getAsLong() will
// return the value
if (obj.isPresent()) {
System.out.println(obj.getAsLong());
}
else {
System.out.println("-1");
}
}
}
输出:
54
示例2:
// Java code for LongStream max()
// to get the maximum value in range
// excluding the last element
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// To find maximum in given range
LongStream stream = LongStream.range(50L, 75L);
// storing the maximum value in variable
// if it is present, else show -1.
long maximum = stream.max().orElse(-1);
// displaying the maximum value
System.out.println(maximum);
}
}
输出:
74
示例3:
// Java code for LongStream max()
// to get the maximum value in range
// excluding the last element
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// To find maximum in given range
LongStream stream = LongStream.range(50L, 50L);
// storing the maximum value in variable
// if it is present, else show -1.
long maximum = stream.max().orElse(-1);
// displaying the maximum value
System.out.println(maximum);
}
}
输出:
-1
相关用法
- Java LongStream min()用法及代码示例
- Java LongStream peek()用法及代码示例
- Java LongStream empty()用法及代码示例
- Java LongStream count()用法及代码示例
- Java LongStream filter()用法及代码示例
- Java LongStream mapToInt()用法及代码示例
- Java LongStream average()用法及代码示例
- Java LongStream noneMatch()用法及代码示例
- Java LongStream allMatch()用法及代码示例
- Java LongStream distinct()用法及代码示例
- Java LongStream anyMatch()用法及代码示例
- Java LongStream reduce(long identity, LongBinaryOperator op)用法及代码示例
- Java LongStream sum()用法及代码示例
- Java LongStream of()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 LongStream max() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。