Java OptionalLong stream()方法及示例
stream() 方法帮助我们以LongStream的形式获得OptionalLong所包含的Long值。如果一个值存在,该方法返回一个只包含该值的连续LongStream,否则返回一个空LongStream。
语法
public LongStream stream()
参数: 此方法不接受任何东西。
返回值: 该方法以LongStream的形式返回可选的值。
下面的程序说明了stream()方法:
程序1 :
// Java program to demonstrate
// OptionalLong.stream() method
import java.util.OptionalLong;
import java.util.stream.LongStream;
public class GFG {
public static void main(String[] args)
{
// create a OptionalLong
OptionalLong opLong
= OptionalLong.of(163252382159472124L);
// get value as stream
LongStream out = opLong.stream();
// print value
System.out.print("Value: ");
out.forEach(System.out::print);
}
}
输出:
程序2 :
// Java program to demonstrate
// OptionalLong.stream() method
import java.util.OptionalLong;
import java.util.stream.LongStream;
public class GFG {
public static void main(String[] args)
{
// create a empty OptionalLong
OptionalLong opLong = OptionalLong.empty();
// get value as stream
LongStream out = opLong.stream();
// print value
System.out.print("length of Long Stream: "
+ out.count());
}
}
输出:
参考文献: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html#empty()