Monday, November 15, 2021

How to use Stream findFirst and findAny function in Java? Example Tutorial

Hello friends, here we are again on the journey of Java excited and eager to find the next stop of knowledge. But do not worry my friends, continuing the java stream series further, today we will deep dive into two other functions of streams that are equally important and interesting.

So what’s the wait? Let’s start!

Let me start by providing a situation that you guys can analyze and then we will discuss it. Let’s say you have data coming into your code through an API call. Now, you have no idea what the stream of data would be but you want the first element present in it. So, stream provides a function for the same. Let’s see what it is and how it is written.



Stream findFirst:


Stream findFirst method returns an Optional<T> object from the stream. Also, the object inside Optional is the first object/data from the stream. So, what if the first element/object in-stream is null? In this case, the Optional object will have null inside it.

Note: the Optional Object itself will never be null but the element/object inside it can be null.

To understand more about it, let’s see an example. We will write a code for finding the first car from a stream/array of cars. Let’s see how it proceeds. suppose we have 6 car names with us stored in an array. Now, we convert about array into a stream (this is done in the below code by using Arrays.stream function).


Now, when we want the first element from the stream, we will utilize our Streams.findFirst() method as shown below. this will return us an Optional object. We have already discussed what an Optional Object is above. let's take a look at the code and observe the output.

Java 8 Stream findFirst and findAny Example



Stream findFirst code:

Now, let's see the Java program which demonstrates how to use the findFirst method from Stream in Java. 

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

public class StreamExample {

public static void main(String[] args) {

String[] carNames = new String[]
{"BMW", "Mercedes", "Audi", "Ferrari", "Tesla", "Maruti 800"};

Optional<String> optional = Arrays.stream(carNames)
.findFirst();
if(optional.isPresent()) {
try {
String result = optional.get();
System.out.println("car you got is: "+result+" :)");
} catch(NullPointerException e) {
System.out.println("NullPointerException occurred," +
" as element inside Optional was Null!");
}
} else {
System.out.println("No car for you :(");
}
}

}



Output:


JAva 8 findFirst and findAny example



So, as seen, we get the first element from the array. Now let’s see what happens when the first element is null. The stream has given a null output. the value was never assigned to Optional even, before that, Nullpointerexception was thrown by stream's findFirst method.





2. Stream findFirst code (NullPointer) :

Now, let's the code example of findFirst() method of Stream class in Java:

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

public class StreamExample {

public static void main(String[] args) {

String[] carNames = new String[]
{null, "BMW", "Mercedes", "Audi", "Ferrari", "Tesla", "Maruti 800"};
try {
Optional<String> optional = Arrays.stream(carNames)
.findFirst();
if (optional.isPresent()) {

String result = optional.get();
System.out.println("car you got is: " + result + " :)");
} else {
System.out.println("No car for you :(");
}
} catch(NullPointerException e) {
System.out.println("NullPointerException occurred," +
" as element from stream is null!");
}

}

}


Output:


So, this was all for findFirst. Now let’s move on to the other method.





2. Stream findAny:


Stream findAny method returns an Optional<T> object from the stream. Also, the object inside Optional is selected randomly from the stream. So, what if the selected element/object in-stream is null? In this case, the Optional object will have null inside it.


Note: the Optional Object itself will never be null but the element/object inside it can be null.


Note that the behavior of the Stream findAny() function is deliberately non-deterministic, meaning that any element in the array/stream can be selected. Multiple calls to the same stream/array may or may not get the same output.


So let’s understand it with the help of code. We will utilize the same code fragment from the previous example for easy understanding. after all, it's all about refactoring and reusability :p


As discussed above, we have the same of 6 car names. Now, we want to find any element from the stream. For this, we will use the Stream.findAny() function. let's see how the code works, its implementation, and the output.


Stream findAny() code:

Here is the complete code example of findAny() method in Java:

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

public class StreamExample {

public static void main(String[] args) {

String[] carNames = new String[] {"BMW", "Mercedes", "Audi", "Ferrari",
"Tesla", "Maruti 800"};

Optional<String> optional = Arrays.stream(carNames).findAny();
if(optional.isPresent()) {
String result = optional.get();
System.out.println("car you got is: "+result+" :)");
} else {
System.out.println("No car for you :(");
}
}

}


Output:


How to use Stream findFirst and findAny function in Java? Example Tutorial




Points to note:

  1. Both these functions are terminal-short-circuiting operations of the stream.

  2. Also, for findAny method, Any initial element that satisfies the intermediate operations is returned by this function. This is a short-circuit operation since all that is required is for the first element to be returned and the iteration to end.

  3. The Java docs explicitly state that FindAny is a non-deterministic operation. This operation's behavior is deliberately nondeterministic; it can choose any element in the stream. This is to provide for maximum parallel speed; nevertheless, successive invocations on the same source may not produce the same result. (If you want a more reliable result, try findFirst() instead.)

  4. Also, for findFirst, the Javadocs state that, If the stream is empty, returns an Optional describing the first element, or an empty Optional if the stream is empty. Any element may be returned if the stream has no encounter order.

So, as understood from the above codes and explanations, you guys must be very familiar very this method now. Feel free to have hands-on and juggle around with these methods.


Till then, happy Java streaming :p


Other Java 8  Lambda and Stream Tutorials You may like


Thanks for reading this tutorial so far. If you like this Java 8 findFirst and FindAny tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are keen to learn Java 8 Functional programming but looking for a free online training course to start with then you can also check out these best Java Functional Programming courses on Udemy. It's completely free and you just need a Udemy account to join this course. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.