findFirst
Optional<T> findFirst()
Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
This is a short-circuiting terminal operation.
Returns:
an Optional describing the first element of this stream, or an empty Optional if the stream is empty
Throws:
NullPointerException - if the element selected is null
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.
This is a short-circuiting terminal operation.
The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
Returns:
an Optional describing some element of this stream, or an empty Optional if the stream is empty
Throws:
NullPointerException - if the element selected is null
See Also:
// streams/SelectElement.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
import static streams.RandInts.*;
public class SelectElement {
public static void main(String[] args) {
System.out.println(rands().findFirst().getAsInt());
System.out.println(
rands().parallel().findFirst().getAsInt());
System.out.println(rands().findAny().getAsInt());
System.out.println(
rands().parallel().findAny().getAsInt());
}
}
/* My Output:
258
258
258
804
*/
For a non-parallel() stream, findAny() chooses the first element (although from the definition it has the option to choose any element). In this example, making the stream parallel() introduces the possibility that findAny() chooses other than the first element.
If we must select the last element in a stream, use reduce():
// streams/LastElement.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
public class LastElement {
public static void main(String[] args) {
OptionalInt last = IntStream.range(10, 20).reduce((n1, n2) -> n2);
System.out.println(last.orElse(-1));
// Non-numeric object:
Optional<String> lastobj = Stream.of("one", "two", "three").reduce((n1, n2) -> n2);
System.out.println(lastobj.orElse("Nothing there!"));
}
}
/* Output:
19
three
*/
OptionalInt reduce(IntBinaryOperator op)
Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an OptionalInt describing the reduced value, if any. This is equivalent to:
boolean foundAny = false;
int result = null;
for (int element : this stream) {
if (!foundAny) {
foundAny = true;
result = element;
}
else
result = accumulator.applyAsInt(result, element);
}
return foundAny ? OptionalInt.of(result) : OptionalInt.empty();
but is not constrained to execute sequentially.
The accumulator function must be an associative function.
This is a terminal operation.
Parameters:
op - an associative, non-interfering, stateless function for combining two values
Returns:
the result of the reduction
See Also:
reduce(int, IntBinaryOperator)
orElse
public int orElse(int other)
Return the value if present, otherwise return other.
Parameters:
other - the value to be returned if there is no value present
Returns:
the value, if present, otherwise other
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/SelectElement.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/RandInts.java
4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#findFirst--
6. https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html#orElse-int-
本文深入探讨Java Stream API中findFirst和findAny方法的区别,以及如何使用reduce方法选择流中的最后一个元素。通过实例演示了非并行流和并行流下findAny方法的行为差异,并解释了reduce方法的工作原理。
5921

被折叠的 条评论
为什么被折叠?



