iterating and filtering two lists using java 8

后端 未结 9 517
抹茶落季
抹茶落季 2020-12-09 17:21

I want to iterate two lists and get new filtered list which will have values not present in second list. Can anyone help?

I have two lists - one is list of strings,

9条回答
  •  孤城傲影
    2020-12-09 17:55

    // produce the filter set by streaming the items from list 2
    // assume list2 has elements of type MyClass where getStr gets the
    // string that might appear in list1
    Set unavailableItems = list2.stream()
        .map(MyClass::getStr)
        .collect(Collectors.toSet());
    
    // stream the list and use the set to filter it
    List unavailable = list1.stream()
                .filter(e -> unavailableItems.contains(e))
                .collect(Collectors.toList());
    

提交回复
热议问题