LongStream findFirst()返回描述此流的第一個元素的OptionalLong(一個可能包含也可能不包含非null值的容器對象),或者返回空的OptionalLong(如果該流為空)
用法:
OptionalLong findFirst()
參數:
- OptionalLong : 可以包含或不包含非null值的容器對象。
返回值:該函數返回描述此流的第一個元素的OptionalLong;如果流為空,則返回一個空的OptionalLong。
注意:findAny()是流接口的terminal-short-circuiting操作。此方法返回滿足中間操作的任何第一個元素。
示例1:長流上的findFirst()方法。
// Java code for LongStream findFirst()
// which returns an OptionalLong describing
// first element of the stream, or an
// empty OptionalLong if the stream is empty.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream
LongStream stream = LongStream.of(6L, 7L, 8L, 9L);
// Using LongStream findFirst() to return
// an OptionalLong describing first element
// of the stream
OptionalLong answer = stream.findFirst();
// if the stream is empty, an empty
// OptionalLong is returned.
if (answer.isPresent())
System.out.println(answer.getAsLong());
else
System.out.println("no value");
}
}
輸出:
6
注意:如果流沒有遇到順序,則可以返回任何元素。
示例2:findFirst()方法返回第一個可被4整除的元素。
// Java code for LongStream findFirst()
// which returns an OptionalLong describing
// first element of the stream, or an
// empty OptionalLong if the stream is empty.
import java.util.OptionalLong;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream
LongStream stream = LongStream.of(4L, 5L, 8L, 10L, 12L, 16L)
.parallel();
// Using LongStream findFirst().
// Executing the source code multiple times
// must return the same result.
// Every time you will get the same
// value which is divisible by 4.
stream = stream.filter(num -> num % 4 == 0);
OptionalLong answer = stream.findFirst();
if (answer.isPresent())
System.out.println(answer.getAsLong());
}
}
輸出:
4
相關用法
- Java IntStream findFirst()用法及代碼示例
- Java Stream findFirst()用法及代碼示例
- Java LongStream of()用法及代碼示例
- Java LongStream sum()用法及代碼示例
- Java LongStream sorted()用法及代碼示例
- Java LongStream limit()用法及代碼示例
- Java LongStream skip()用法及代碼示例
- Java LongStream sequential()用法及代碼示例
- Java LongStream summaryStatistics()用法及代碼示例
- Java LongStream max()用法及代碼示例
- Java LongStream concat()用法及代碼示例
- Java LongStream iterator()用法及代碼示例
- Java LongStream min()用法及代碼示例
- Java LongStream range()用法及代碼示例
- Java LongStream toArray()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream findFirst() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。