Java中的LongStream max()及其示例

JAVAutil。流动Java 8中的LongStream处理原始long。它以一种新的方式解决了数组中求最大值、求最小值、求数组中所有元素之和、求数组中所有值的平均等问题。 LongStream max() 返回一个OptionalLong来描述 最大限度 元素,如果此流为空,则为空可选。

null

语法:

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
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享