Java 8 lambda 空列表空检查

标签 java lambda java-8 java-stream

我正在尝试执行 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/

相关文章:

Java 8 : Map Lambda expression

java - 取消申请使用谷歌账户的权利

java - 在控制台管理多个线程

python - ** lambda 函数列表理解中的 kwargs

c# - 如何使用Lambda表达式选择特定项目?

java - 使用 Java 8 流将 List<E> 转换为 Map<String, List<String>>

java - 2D 裁剪区域以形成形状

java - TableModel 与 ColumnModel : who owns the column value?

c# - 委托(delegate) System.Action 不接受 1 个参数

java - 不能在流 forEach 中使用 System.out.println