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;

Nicholas K :

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35268&siteId=1