“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022”
Writing in the front
Since JDK8 came out, many programming methods have changed, such as functional programming, Lambda expressions, which make our programming more efficient.
Among them, the STREAM-related API in JDK8 greatly improves the efficiency of our actual development. Instead of using ten lines of code, we can now use one line of code with higher efficiency.
I am learning Stream recently, so I hereby record some necessary questions, hoping to help you.
The problem
Today’s question is what is the difference between findAny and findFirst in a Stream?
If it is used improperly in the work, some very troublesome problems will suddenly break out with the extension of the project running time. Meeting doubts, solving doubts, is the fundamental place.
answer
First, both methods are used to find and return the first element object in the queried list, which is somewhat different.
Let’s take a look at an example of code we normally use.
The specific application code is as follows:
List<String> list0 = Arrays.asList("Ji Xiaolan"."The declaration"."Yellow"."Zhang"."Zhang four"."The four yellow");
List<String> list1 = Arrays.asList("Ji Xiaolan"."The declaration"."Yellow"."Zhang"."Zhang four"."The four yellow");
Optional<String> findFirst = list0.Stream().filter(s -> s.startsWith("Zhang")).findFirst();
Optional<String> fidnAny = list1.Stream().filter(s -> s.startsWith("Zhang")).findAny();
System.out.println(findFirst.get());
System.out.println(fidnAny.get()); // Randomly prints Jack/Jill/Julia
Copy the code
The output of the first line, no matter how many times it is executed, will only print “zhang SAN”.
The output of the second line will randomly print out threes and fours.
The findAny method returns an element at random, so if there are multiple values, there is no guarantee that the elements returned multiple times are consistent.
The findFrist method actually returns the first element object in the collection.
conclusion
As our example shows, the difference between findAny and findFirst is that the former method randomly finds matched elements, while the latter method takes only the element with the smallest set index, i.e. the first element object that is iterated in sequence.