$show=/label

Java 8 Stream findFirst() vs findAny() With Examples

SHARE:

A quick guide and in-depth understand the differences between the findFirst() and findAny() methods in java 8 stream api.

1. Overview

In this article, you'll learn what are the differences between findFirst() and findAny() in java 8 Streams.

These methods are quite makes confusion to the some developers.

Let us understand findFirst() vs findAny() first and learn when to use right one.

Read more on :


findAny() and findFirst() are stream terminal operations that means produces the final result.

If any one the stream values is null then it will NullPointerException.
List<String> values = Arrays.asList("A", "B", null, "F", "D");
Optional<String> anyValue = values.stream().findFirst();
Output:
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Objects.requireNonNull(Objects.java:221)
	at java.base/java.util.Optional.<init>(Optional.java:107)
	at java.base/java.util.Optional.of(Optional.java:120)
	at java.base/java.util.stream.FindOps$FindSink$OfRef.get(FindOps.java:194)
	at java.base/java.util.stream.FindOps$FindSink$OfRef.get(FindOps.java:191)
	at java.base/java.util.stream.FindOps$FindTask.doLeaf(FindOps.java:319)
	at java.base/java.util.stream.AbstractShortCircuitTask.compute(AbstractShortCircuitTask.java:115)
	at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
	at java.base/java.util.concurrent.ForkJoinTask.doInvoke(ForkJoinTask.java:408)
	at java.base/java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:736)
	at java.base/java.util.stream.FindOps$FindOp.evaluateParallel(FindOps.java:160)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
	at java.base/java.util.stream.ReferencePipeline.findAny(ReferencePipeline.java:548)
	at com.javaprogramto.java8.streams.find.FindAnyParallelStreamIntegersExample.main(FindAnyParallelStreamIntegersExample.java:15)

2. Understand Usage of Stream.findAny()


By seeing the name of the method, you can assume that it is going to return any value from stream. Yes, you are correct till this point.

But, if you are not worried about the order how the values are appearing in the list or stream.

Syntax:
Optional<T> findAny()

This method returns Optional instance with the value found and returns empty Optional if the stream is empty.
package com.javaprogramto.java8.streams.find;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FindAnyExample {

	public static void main(String[] args) {

		// creating a list with string values
		List<String> values = Arrays.asList("A", "B", "C", "F", "D");

		// getting the any value from stream.
		Optional<String> anyValue = values.stream().findAny();

		// printing the value
		if (anyValue.isPresent()) {
			System.out.println("Any value from stream : " + anyValue.get());
		} else {
			System.out.println("No value presnt in the stream.");
		}
	}
}

Output:
Any value from stream : A
It has obtained the first value from the stream that is value "A". So, it gets the first value from stream.

Now, the tricky part is if the stream is parallel then it will not return the first value but not guaranteed.

For the same list, called findAny() method on parallel stream.
Optional<String> anyValue = values.stream().parallel().findAny();
Now let us see the output. Look at the below output.
Any value from stream : C
So, the value is changed in case stream is parallel and value cannot be predicted.

Next, let us have a look at another example on parallel stream.
package com.javaprogramto.java8.streams.find;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FindAnyParallelStreamIntegersExample {

	public static void main(String[] args) {

		// creating a list with integer prime values
		List<Integer> values = Arrays.asList(2, 3, 5, 7, 11);

		// Creating prallel stream.
		Optional<Integer> anyValue = values.stream().parallel().findAny();

		// printing the value
		if (anyValue.isPresent()) {
			System.out.println("Value from integer stream : " + anyValue.get());
		} else {
			System.out.println("No value presnt in the stream.");
		}
	}
}
Output:
Value from integer stream : 5

3. Understand Usage of Stream.findFirst()


As this method name describes, findFirst() method returns the first value from stream for any type of stream it may be sequential or parallel.

This method also returns Optional object with the first value. If the stream is empty then empty Optional is returned.

Let see the examples with sequential and parallel streams.

Sequential Stream:
package com.javaprogramto.java8.streams.find;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FindFirstSequentialExample {

	public static void main(String[] args) {

		// creating a list with string values
		List<String> values = Arrays.asList("A", "B", "C", "F", "D");

		// Getting the first value from sequential stream using findFirst() method
		Optional<String> anyValue = values.stream().findFirst();

		// printing the value
		if (anyValue.isPresent()) {
			System.out.println("First value from stream : " + anyValue.get());
		} else {
			System.out.println("No value presnt in the stream.");
		}
	}
}
Output:
First value from stream : A

Parallel Stream:
package com.javaprogramto.java8.streams.find;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FindFirstParallelExample {

	public static void main(String[] args) {

		// creating a list with string values
		List<String> values = Arrays.asList("A", "B", "C", "F", "D");

		// Getting the first value from sequential stream using findFirst() method
		Optional<String> anyValue = values.stream().parallel().findFirst();

		// printing the value
		if (anyValue.isPresent()) {
			System.out.println("First value from parallel stream : " + anyValue.get());
		} else {
			System.out.println("No value presnt in the stream.");
		}
	}
}
Output:
First value from parallel stream : A

From the above two sequential and parallel streams outputs, findFirst() method returns always the same output.

4. Conclusion


In this tutorial, you've seen the all the differences between the findFirst() and findAny() method in java 8.
 
Main similarity is findFirst() and findAny() method returns the first value from the stream if it is sequential. By default, stream is created with sequential pattern. And always both methods returns the same value. if the any value in the stream is null then it will throw NullPointerException.

But, if you working with parallel streams and your intention is to get the first value from stream then use only findFirst() method. But findAny() method works differently with parallel streams and may get any value from stream (mostly first one but not guaranteed).Because, among the parallel threads, which ever thread is started first and what ever the element is picked from the stream is considered as first value.

GitHub


Read Next

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Stream findFirst() vs findAny() With Examples
Java 8 Stream findFirst() vs findAny() With Examples
A quick guide and in-depth understand the differences between the findFirst() and findAny() methods in java 8 stream api.
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-stream-findfirst-vs-findany.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-stream-findfirst-vs-findany.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content