Get an element from a list in a Nested optional check

karvai :

I have the following nested null check which. Trying to make it readable via Optional but how do I map a first element?

Stuck with following, unsure how to map this line

vo.getSomething().getAnother().get(0)

I am stuck on the 3rd line

Optional.of(vo.getSomething)
    .map(Something::getAnother)
    .map(List<Another>::get(0)) // will not work

Here is a working null check. I am trying to clean it up with Optional.

if(vo.getSomething() != null){
    if(vo.getSomething().getAnother() != null){
        if(vo.getSomething().getAnother().get(0) != null){
            if(vo.getSomething().getAnother().get(0).getInner() != null){
                if(vo.getSomething().getAnother().get(0).getInner() != null){
                    if(vo.getSomething().getAnother().get(0).getInner().get(0) != null){
                        return vo.getSomething().getAnother().get(0).getInner().get(0).getProductName();
                    }
                }
            }
        }
    }
}
Andrew Tobilko :

A lambda expression

.map(list -> list.get(0))

should work. Some ideas can't be expressed by method references.

List<Another>::get(0) isn't a valid method reference while List<Another>::get can be.

BiFunction<List<String>, Integer, String> function = List::get;

The problem with that expression is that it has a constant 0 and you need to pass it explicitly.

However, you could write a static method

class ListFunctions {
    public static <T> T getFirst(List<? extends T> list) {
        return list.get(0);
    }
}

and refer to it via a method reference

.map(ListFunctions::getFirst)

Guess you like

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