Introduction to the

More recently, writing using the Java 8 Stream API has introduced two oft-misunderstood methods: findAny() and findFirst(). Again the difference between these two methods and when to use it to make a note,

Using Stream. FindAny ()

The findAny() method allows you to findAny element in a Stream without noticing the order of encounter. This method returns an Optional instance that is null if Stream is null.

@Test
public void createStream_whenFindAnyResultIsPresent_thenCorrect(a) {
    List<String> list = Arrays.asList("A"."B"."C"."D");
 
    Optional<String> result = list.stream().findAny();
 
    assertTrue(result.isPresent());
    assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
}
Copy the code

In parallel operations, it might return the first element in the Stream, but the game is not guaranteed. For optimal performance when handling parallel operations, the result cannot be reliably determined:

@Test
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect(a)(a) {
    List<Integer> list = Arrays.asList(1.2.3.4.5);
    Optional<Integer> result = list
      .stream().parallel()
      .filter(num -> num < 4).findAny();
 
    assertTrue(result.isPresent());
    assertThat(result.get(), anyOf(is(1), is(2), is(3)));
}
Copy the code

Using Stream. FindFirst ()

Use the findFirst() method to find the first element in the stream. This method is used when the first element in the sequence is particularly needed. If no order is encountered, it returns any elements from the Stream. The ‘java.util.stream’ package says:

A flow may or may not have a defined order of encounters, depending on the source and intermediate operations

The return type is also Optional, which is also null if Stream is also empty:

@Test
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
 
    List<String> list = Arrays.asList("A", "B", "C", "D");
 
    Optional<String> result = list.stream().findFirst();
 
    assertTrue(result.isPresent());
    assertThat(result.get(), is("A"));
}
Copy the code

In a parallel scenario, the behavior of the findFirst() method does not change. If the encountered order exists, it will always be deterministic.

conclusion

  • findAny()Method is used to return streams from any element
  • findFirst()Method returns in the first element stream

As shown in the

Java 8 Stream findFirst() and findAny()