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. 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.
1. Stream findFirst Example
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.
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:
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) Example
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.
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:
Points to note:
-
Both these functions are terminal-short-circuiting operations of the stream.
-
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.
-
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.)
- Also, for findFirst, the Java docs 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.
Till then, happy Java streaming :p
Other Java 8 Lambda and Stream Tutorials You may like
- 5 Free Java 8 and Java 9 Courses for Developers
- How to do Map Reduce in Java 8?
- How to use flatMap in Java 8?
- 10 examples of the forEach() method in Java 8?
- 3 ways to read a file line by line in Java 8
- 10 examples of converting a List<V> to Map of <K, V> in Java 8?
- Top 5 Books to Learn Java 8 Better
- 10 Courses to learn Java for Beginners
- My favorite courses to learn Software Architecture
- Java 8 filter + map + collect example
- 10 Free Courses to learn Spring Framework for Beginners
- How to pass the Java SE 11 Certification Exam
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.