streams - Operations on Optional Objects

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-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值