我试图访问内部对象而不会导致空指针异常。 我希望避免手动写入if条件null检查并使用java 8的功能。
我从findFirst方法获取Nullpointer异常。我知道如果selected元素为null,则findFirst返回空指针异常,所以我尝试在调用findFirst之前使用filter(Objects :: nonNull)过滤掉null对象,但它仍然抛出空指针。
看起来我的过滤功能不起作用,但我不知道原因。
Please find below the code
package main.java;
import java.util.*;
import java.util.stream.Stream;
public class OptionalTest {
public static void main(String args[]) {
Inner in = new Inner("Has Value");
Nested nest = new Nested(in);
List<Nested> list = new ArrayList<Nested>();
//list.add(nest); //commented out to test failure scenario
list.add(null); //added null
list.add(null); //added null
Outer outer = new Outer(list);
OuterMost outermost = new OuterMost(outer);
Optional<String> innerValue = Optional.ofNullable(outermost) // outermost var can be null, hence using Optional.ofNullable
.map(OuterMost::getOuter)
.map(Outer::getNested)
.map(Collection::stream)
.filter(Objects::nonNull) //findFirst throws null pointer if selected element is null, hence filtering out null
.flatMap(Stream::findFirst)
.map(Nested::getInner)
.map(Inner::getFoo);
System.out.println(innerValue.orElse("No Value"));
}
}
//Classes OuterMost>Outer>Nested(List)>Inner
class OuterMost {
public OuterMost(Outer out) {
outer = out;
}
Outer outer;
Outer getOuter() {
return outer;
}
}
class Outer {
public Outer(List<Nested> nest) {
nested = nest;
}
List<Nested> nested;
List<Nested> getNested() {
return nested;
}
}
class Nested {
public Nested(Inner in) {
inner = in;
}
Inner inner;
Inner getInner() {
return inner;
}
}
class Inner {
public Inner(String val) {
foo = val;
}
String foo;
String getFoo() {
return foo;
}
}