简体   繁体   English

使用Java 8获取列表的最后一个非null元素

[英]Get last not null element of list by using Java 8

In Java 7, if I want to get the last not null element of a list, I write something like this: 在Java 7中,如果我想获取列表的最后一个非null元素,我写这样的东西:

public CustomObject getLastObject(List<CustomObject> list) {
    for (int index = list.size() - 1; index > 0; index--) {
        if (list.get(index) != null) {
            return list.get(index);
        }
    }
    // handling of case when all elements are null
    // or list is empty
    ...
}

I want to write a shorter code by using lambdas or another feature of Java 8. For example, if I want to get the first not null element I can write this: 我想通过使用lambdas或Java 8的另一个特性来编写更短的代码。例如,如果我想获得第一个非null元素,我可以这样写:

public void someMethod(List<CustomObject> list) {
    .....
    CustomObject object = getFirstObject(list).orElseGet(/*handle this case*/);
    .....
}

public Optional<CustomObject> getFirstObject(List<CustomObject> list) {
    return list.stream().filter(object -> object != null).findFirst();
}

Maybe someone know how to solve this problem? 也许有人知道如何解决这个问题?

A possible solution would be to iterate over the List in reverse order and keep the first non null element: 一种可能的解决方案是以相反的顺序迭代List并保留第一个非null元素:

public Optional<CustomObject> getLastObject(List<CustomObject> list) {
    return IntStream.range(0, list.size()).mapToObj(i -> list.get(list.size() - i - 1))
                                          .filter(Objects::nonNull)
                                          .findFirst();
}

Note that there is no findLast method in the Stream API because a Stream is not necessarily ordered or finite. 请注意,Stream API中没有findLast方法,因为Stream不一定是有序的或有限的。

Another solution is to iterate over the list and reduce it by keeping only the current element. 另一个解决方案是迭代列表并通过仅保留当前元素来减少它。 This effectively reduces the Stream to the last element. 这有效地将Stream减少到最后一个元素。

public Optional<CustomObject> getLastObject(List<CustomObject> list) {
    return list.stream().filter(Objects::nonNull).reduce((a, b) -> b);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM