簡體   English   中英

Java 8 Lambda空列表進行空檢查

[英]Java 8 lambda null list to empty check

我正在嘗試對null列表進行null檢查,如果值為null.則將其更改為null. 我正在將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.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(...)

您可以簡單地使用以下方法找到這樣的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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM