Three methods (in class Optional)enable post-processing on Optionals, so if our stream pipeline produces an Optional you can do one more thing at the end:
If a value is present, and the value matches the given predicate, return an Optional
describing the value, otherwise return an empty Optional
.
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional
describing the result.
If a value is present, apply the provided Optional
-bearing mapping function to it, return that result, otherwise return an empty Optional
.
For exmaple:
// streams/OptionalFilter.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.function.*;
import java.util.stream.*;
class OptionalFilter {
static String[] elements = {"Foo", "", "Bar", "Baz", "Bingo"};
static Stream<String> testStream() {
return Arrays.stream(elements);
}
static void test(String descr, Predicate<String> pred) {
System.out.println(" ---( " + descr + " )---");
for (int i = 0; i <= elements.length; i++) { // note i can be elements.length
System.out.println(testStream().skip(i).findFirst().filter(pred));
}
}
public static void main(String[] args) {
test("true", str -> true);
test("false", str -> false);
test("str != \"\"", str -> str != "");
test("str.length() == 3", str -> str.length() == 3);
test("startsWith(\"B\")", str -> str.startsWith("B"));
}
}
/* Output:
---( true )---
Optional[Foo]
Optional[]
Optional[Bar]
Optional[Baz]
Optional[Bingo]
Optional.empty
---( false )---
Optional.empty
Optional.empty
Optional.empty
Optional.empty
Optional.empty
Optional.empty
---( str != "" )---
Optional[Foo]
Optional.empty
Optional[Bar]
Optional[Baz]
Optional[Bingo]
Optional.empty
---( str.length() == 3 )---
Optional[Foo]
Optional.empty
Optional[Bar]
Optional[Baz]
Optional.empty
Optional.empty
---( startsWith("B") )---
Optional.empty
Optional.empty
Optional[Bar]
Optional[Baz]
Optional[Bingo]
Optional.empty
*/
interface two methods:
Stream<T> skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n
elements of the stream. If this stream contains fewer than n
elements then an empty stream will be returned.
This is a stateful intermediate operation.
API Note:
While skip()
is generally a cheap operation on sequential stream pipelines, it can be quite expensive on ordered parallel pipelines, especially for large values of n
, since skip(n)
is constrained to skip not just any n elements, but the first n elements in the encounter order. Using an unordered stream source (such as generate(Supplier)
) or removing the ordering constraint with BaseStream.unordered()
may result in significant speedups of skip()
in parallel pipelines, if the semantics of your situation permit. If consistency with encounter order is required, and you are experiencing poor performance or memory utilization with skip()
in parallel pipelines, switching to sequential execution with BaseStream.sequential()
may improve performance.
Parameters:
n
- the number of leading elements to skip
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.
final class Optional's one method:
public Optional<T> filter(Predicate<? super T> predicate)
If a value is present, and the value matches the given predicate, return an Optional
describing the value, otherwise return an empty Optional
.
Parameters:
predicate
- a predicate to apply to the value, if present
Returns:
an Optional
describing the value of this Optional
if a value is present and the value matches the given predicate, otherwise an empty Optional
Throws:
NullPointerException
- if the predicate is null
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/OptionalFilter.java
3. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
4. https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps
6. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-