Java 8 Lambda空列表进行空检查

时间:2019-01-09 18:17:24

标签: java lambda java-8 java-stream

我正在尝试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 example = new Example(); example.setTest(test);

    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())))

2 个答案:

答案 0 :(得分:2)

将一个复杂的流步骤分解成多个简单的步骤通常更简单,更易读:

list1.stream()
     .map(SomeCall::getSomeCall)
     .filter(Objects::nonNull)
     .flatMap(Collection::stream)   // or List::stream if it's a list
     .collect(...)

答案 1 :(得分:1)

您可以使用以下方法找到这样的sum

int size = stList.stream() // variable renamed not to start with numeric
        .mapToInt(st -> Optional.ofNullable(st.getSomeCall()).map(List::size).orElse(0))
        .sum();

已更新问题

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());

  

获取值列表,而不是大小

如果结果是获得List<Test2>,尽管您也可以将其获取为:

List<Test2> list = example.getTest().stream()
        .map(a -> a.getTest2() == null ? new ArrayList<Test2>() : a.getTest2())
        .flatMap(List::stream)
        .collect(Collectors.toList());