[英]Java 8 lambda null list to empty check
I am trying to do null
check for the list of values and change it to empty if the value is null.
我正在尝试对null
列表进行null
检查,如果值为null.
则将其更改为null.
I am getting null as one of the list of value in x.getSomeCall().The null value is not getting added as empty list in the new list 我正在将null作为x.getSomeCall()中的值列表之一。在新列表中未将null值添加为空列表
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 example=new Example(); Example example = new Example(); example.setTest(test); 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[]
}
So that later I can do an empty check with the new list 这样以后我就可以对新列表进行空检查
if(isEmpty(example.getTest().stream()
.flatMap(x -> x.getTest2() == null ? Stream.empty() : x.getTest2().stream())
.collect(Collectors.toList())))
It's often simpler and more readable to break up a complex stream step into into multiple simple ones: 将一个复杂的流分解成多个简单的步骤通常更简单,更易读:
list1.stream()
.map(SomeCall::getSomeCall)
.filter(Objects::nonNull)
.flatMap(Collection::stream) // or List::stream if it's a list
.collect(...)
You could instead find such a sum
simply using: 您可以简单地使用以下方法找到这样的sum
:
int size = stList.stream() // variable renamed not to start with numeric
.mapToInt(st -> Optional.ofNullable(st.getSomeCall()).map(List::size).orElse(0))
.sum();
Updated with question : 更新问题 :
System.out.println(example.getTest().stream() // variable renamed not to start with numeric
.mapToInt(st -> Optional.ofNullable(st.getTest2()).map(List::size).orElse(0))
.sum());
get the list of value instead of size 获取值列表而不是大小
If you were to get the List<Test2>
as a result, your existing code is good enough, though you can also get it as : 如果要获得List<Test2>
的结果,那么您现有的代码就足够了,尽管您也可以将其获取为:
List<Test2> list = example.getTest().stream()
.map(a -> a.getTest2() == null ? new ArrayList<Test2>() : a.getTest2())
.flatMap(List::stream)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.