• ①. Stream的findFirst方法在此流中查找第一个元素作为Optional,如果流中没有元素,findFirst返回空的Optional,如果findFirst选择的元素为null,它将抛出NullPointerException
    Optional findFirst()

  • ②. findAny():返回流中的任意一个元素;如果流是空的,则返回空

  1. 对于串行流,输出的都是查找第一个元素
  2. 对于并行流,随机获取
/** * Returns an {@link Optional} describing the first element of this stream, * or an empty {@code 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. * * @return an {@code Optional} describing the first element of this stream, * or an empty {@code Optional} if the stream is empty * @throws NullPointerException if the element selected is null * 返回一个描述次流的第一个元素的Optional,如果流为空,则返回一个空的Optional,如果没有遇到顺序,则可以返回任何元素 * 这是一个短路终端操作 * 抛出: NullPointException - 如果选择的元素为null */Optional<T> findFirst();/** * Returns an {@link Optional} describing some element of the stream, or an * empty {@code 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 {@link #findFirst()} instead.) * * @return an {@code Optional} describing some element of this stream, or an * empty {@code Optional} if the stream is empty * @throws NullPointerException if the element selected is null * @see #findFirst() * 返回一个描述流的某些元素的Optional,如果流为空,则返回一个空Optional * 这是一个短路终端操作 * 这个流操作的行为是明确的非确定下的,可以自由选择流中的任何元素。这是为了在并行操作中实现最大的性能。 * 代价是对同一源多次调用可能不会返回相同的结果(如果需要稳定的结果,使用findFirst()) * 抛出: NullPointException - 如果选择的元素为null */Optional<T> findAny();

  • ③. 假设我们有一个整数流,并对其调用findFirst方法
public class FindFirstDemo1 {public static void main(String[] args) {List<String> list = Arrays.asList("Vijay", "Suresh", "Vinod");String output = list.stream().filter(e -> e.startsWith("V")) // Vijay, Vinod.findFirst() //Vijay.orElse("NA");// VijaySystem.out.println(output);List<Integer> numList = Arrays.asList(31, 32, 33, 34);numList.stream().filter(n -> n % 2 == 0) // 32, 34.findFirst() //32.ifPresent(e -> System.out.println(e));//32}} 
//0.准备一个数组String[] strs = {"aaa","bbb","ccc","ddddd","abcdefg"};// 1.查找第一个元素Optional<String> first = Stream.of(strs).findFirst();System.out.println("获取第一个元素 : "+first.get()); // 通过Optional的get()方法取值//2.查找任意一个元素 - > 对于串行流,输出的都是查找第一个元素Optional<String> any = Stream.of(strs).findAny();System.out.println("获取任意一个元素 :"+any.get()); // 通过Optional的get()方法取值//2.查找任意一个元素 - > 对于并行流,随机获取Optional<String> parallelFindAny = Arrays.asList(strs).parallelStream().findAny();System.out.println("获取任意一个元素 :"+parallelFindAny.get()); // 通过Optional的get()方法取值