Home » Core Java » Java 8 Stream – findAny() & findFirst() Example

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Java 8 Stream – findAny() & findFirst() Example

Hello. In this tutorial, we will explain the findAny() and findFirst() methods in java 8.

1. Introduction

java 8 findAny

Before diving deep into the practice stuff let us understand the findAny() and findFirst() methods in java8 programming.

  • Stream.findFirst() – Returns an optional object containing first element of the given stream. It can also return an empty() optional if the stream is empty
  • Stream.findAny() – Returns an optional object containing any one element of the given stream. It can also return an empty() optional if the stream is empty

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Utility class

Create a java file in the com.java8.util package and add the following code. The class will act as a utility class for the creation of the house list.

House.java

package com.java8.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

enum Type {
    COTTAGE,
    COLONIAL,
    FARMHOUSE,
    FRENCH_COUNTRY,
    CAPE_GOD
}

public class House {
    private final int id;
    private final String name;
    private final String type;

    private House(final int id, final String name, final String type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

    public static List<House> createHouses() {
        final List<House> houses = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final Type type = Type.values()[new Random().nextInt(5)];
            houses.add(new House(i, "house-" + i, type.name()));
        }
        return houses;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "House{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
}

2.2 Understanding methods

Create a java file in the com.java8 package and add the following code. The class will show the implementation of the findAny() and findFirst() methods.

Demo1.java

package com.java8;

import com.java8.util.House;

import java.util.Optional;

public class Demo1 {

    /*
    Stream.findAny() - Returns an optional object containing any one element of the given stream.
    It can also return an empty() optional if the stream is empty.
    Optional<T> findAny()
    */
    private static void findAnyImplementation() {
        System.out.println("----- findAny() implementation -----");
        final Optional<House> optional = House.createHouses()
                .stream()
                .filter(house -> house.getType().equals("COTTAGE"))
                .findAny();

        if (optional.isPresent()) {
            System.out.println(optional.get());
        } else {
            System.out.println("No data");
        }
    }

    /*
    Stream.findFirst() - Returns an optional object containing first element of the given stream.
    It can also return an empty() optional if the stream is empty.
    Syntax :- Optional<T> findFirst()
    */
    private static void findFirstImplementation() {
        System.out.println("\n----- findFirst() implementation -----");
        final Optional<House> optional = House.createHouses()
                .stream()
                .filter(house -> house.getType().equals("FARMHOUSE"))
                .findFirst();

        if (optional.isPresent()) {
            System.out.println(optional.get());
        } else {
            System.out.println("No data");
        }
    }

    public static void main(String[] args) {
        findAnyImplementation();
        findFirstImplementation();
    }
}

Run the file and if everything goes well the following output will be logged in the IDE console.

Console output

----- findAny() implementation -----
House{id=1, name='house-1', type='COTTAGE'}

----- findFirst() implementation -----
House{id=2, name='house-2', type='FARMHOUSE'}

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned findAny() and findFirst() methods introduced in java8 programming along with the implementation. The two methods are used to find anyone or the first element from the given stream. You can download the source code from the Downloads section.

4. Download the Project

This was a tutorial on learning and implementing the findAny() and findFirst() methods in java8 programming.

Download
You can download the full source code of this example here: Java 8 Stream – findAny() & findFirst() Example

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments