Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream find match or the last one?

How to find the first match or the last element in a list using java stream?

Which means if no element matches the condition,then return the last element.

eg:

OptionalInt i = IntStream.rangeClosed(1,5)
                         .filter(x-> x == 7)
                         .findFirst();
System.out.print(i.getAsInt());

What should I do to make it return 5;

like image 612
金潇泽 Avatar asked Dec 06 '18 08:12

金潇泽


People also ask

How do I find the last element of a stream?

The other way to get the last element of the stream is by skipping all the elements before it. This can be achieved using Skip function of Stream class. Keep in mind that in this case, we are consuming the Stream twice so there is some clear performance impact.

What's the difference between findFirst () and findAny ()?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

Which is faster findAny or findFirst?

Stream findFirst() vs findAny() – Conclusion Use findAny() to get any element from any parallel stream in faster time.

What is the difference between the anyMatch () and findAny () stream methods?

Stream#anyMatch() returns a boolean while Stream#findAny() returns an object which matches the predicate.


2 Answers

Given the list

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

You could just do :

int value = list.stream().filter(x -> x == 2)
                         .findFirst()
                         .orElse(list.get(list.size() - 1));

Here if the filter evaluates to true the element is retrieved, else the last element in the last is returned.

If the list is empty you could return a default value, for example -1.

int value = list.stream().filter(x -> x == 2)
                         .findFirst()
                         .orElse(list.isEmpty() ? -1 : list.get(list.size() - 1));
like image 143
Nicholas Kurian Avatar answered Oct 18 '22 21:10

Nicholas Kurian


You can use reduce() function like that:

OptionalInt i = IntStream.rangeClosed(1, 5)
        .reduce((first, second) -> first == 7 ? first : second);
System.out.print(i.getAsInt());
like image 7
statut Avatar answered Oct 18 '22 20:10

statut