Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

1. Overview

The Java 8 Stream API introduced two methods that are often misunderstood: findAny() and findFirst().

In this quick tutorial, we'll look at the difference between these two methods and when to use them.

Further reading:

Filtering a Stream of Optionals in Java

A quick and practical guide to filtering Streams of Optionals in Java 8 and Java 9

Primitive Type Streams in Java 8

A quick and practical guide to using Java 8 Streams with primitive types.

Iterable to Stream in Java

The article explains how to convert an Iterable to Stream and why the Iterable interface doesn't support it directly.

2. Using Stream.findAny()

As the name suggests, the findAny() method allows us to find any element from a Stream. We use it when we're looking for an element without paying an attention to the encounter order:

The method returns an Optional instance, which is empty if the Stream is empty:

@Test
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
    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")));
}

In a non-parallel operation, it will most likely return the first element in the Stream, but there is no guarantee for this.

For maximum performance when processing the parallel operation, the result cannot be reliably determined:

@Test
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect()() {
    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)));
}

3. Using Stream.findFirst()

The findFirst() method finds the first element in a Stream. So, we use this method when we specifically want the first element from a sequence.

When there is no encounter order, it returns any element from the Stream. According to the java.util.streams package documentation, “Streams may or may not have a defined encounter order. It depends on the source and the intermediate operations.”

The return type is also an Optional instance, which is empty if the Stream is empty too:

@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"));
}

The behavior of the findFirst method does not change in the parallel scenario. If the encounter order exists, it will always behave deterministically.

4. Conclusion

In this article, we looked at the findAny() and findFirst() methods of the Java 8 Streams API.

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

The complete source code and all code snippets for this article are over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!