本文主要介绍通过List的Stream()方法,过滤获取指定元素,获取不到就取最后一个元素的方法。

示例List

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

推荐文档