Java 8 lambda get and remove element from list

后端 未结 12 1552
说谎
说谎 2020-12-08 12:47

Given a list of elements, I want to get the element with a given property and remove it from the list. The best solution I found is:

Produce         


        
12条回答
  •  有刺的猬
    2020-12-08 13:12

    The below logic is the solution without modifying the original list

    List str1 = new ArrayList();
    str1.add("A");
    str1.add("B");
    str1.add("C");
    str1.add("D");
    
    List str2 = new ArrayList();
    str2.add("D");
    str2.add("E");
    
    List str3 = str1.stream()
                            .filter(item -> !str2.contains(item))
                            .collect(Collectors.toList());
    
    str1 // ["A", "B", "C", "D"]
    str2 // ["D", "E"]
    str3 // ["A", "B", "C"]
    

提交回复
热议问题