streams - Selecting an Element

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:

findFirst()

// 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 associativenon-interferingstateless 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--

5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#reduce-java.util.function.IntBinaryOperator-

6. https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html#orElse-int-

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值