示例ListList list = Arrays.asList(1, 2, 3, 4, 5);
1、通过Stream()来获取
如果过滤器的计算结果为true,则检索该元素,否则返回最后一个元素。int value = list.stream().filter(x -> x == 2)
.findFirst()
.orElse(list.get(list.size() - 1));
列表为空,则可以返回默认值,例如-1。int value = list.stream().filter(x -> x == 2)
.findFirst()
.orElse(list.isEmpty() ? -1 : list.get(list.size() - 1));
2、通过for循环来实现public static T getFirstMatchingOrLast(List extends T> source, Predicate super T> predicate){
// handle empty case
if(source.isEmpty()){
return null;
}
for(T t : source){
if(predicate.test(t)){
return t;
}
}
return source.get(source.size() -1);
}
可以这样调用:Integer match = getFirstMatchingOrLast(ints, i -> i == 7);
本文介绍了如何在Java中使用Stream API和for循环从列表中获取第一个匹配项,或者在没有找到匹配项时返回最后一个元素。通过示例展示了如何在列表为空时提供默认值,并提供了相应的for循环实现方式。
4万+

被折叠的 条评论
为什么被折叠?



