我正在尝试执行 null
检查值列表,如果值为 null,则将其更改为空。
我将 null 作为列表之一x.getSomeCall() 中的值。空值不会作为空列表添加到新列表中
public class Example{
private List<Test> test;
//setter
//getter
}
public class Test{
private List<Test2> test2;
//setter
//getter
}
public class Test2{
private String name;
//setter
//getter
}
public static void main(String args[]){
例子 example=new Example(); example.setTest(测试);
List<Test> test=new ArrayList<>();
Test t=new Test();
t.setTest2(test);
Test t1=new Test();
Test t2=new Test();
test.add(t);
test.add(t1);
List<Test2> test=new ArrayList<>();
Test2 t=new Test2();
test.add(t);
test.add(null); // I want to get these value as empty list along with the 1st Value in a new list
//Imperative Programming
for(Example ex:example.getTest()){
System.out.println(ex.getTest2());/It prints t object and a null vale
}
When I tried the same with reactive
List<Test2> t=example.getTest().stream()
.flatMap(x -> x.getTest2() == null ? Stream.empty() : x.getTest2().stream())
.collect(Collectors.toList());
System.out.println(t)// It prints only t object
I was expecting two element on with t object and the other one as empty list[]
}
以便稍后我可以对新列表进行空检查
if(isEmpty(example.getTest().stream()
.flatMap(x -> x.getTest2() == null ? Stream.empty() : x.getTest2().stream())
.collect(Collectors.toList())))
最佳答案
将一个复杂的流步骤分解成多个简单的步骤通常更简单且更具可读性:
list1.stream()
.map(SomeCall::getSomeCall)
.filter(Objects::nonNull)
.flatMap(Collection::stream) // or List::stream if it's a list
.collect(...)
关于Java 8 lambda 空列表空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116111/