iterating and filtering two lists using java 8

this can be achieved using below...

 List<String> unavailable = list1.stream()
                            .filter(e -> !list2.contains(e))
                            .collect(Collectors.toList());

// 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<String> unavailableItems = list2.stream()
  .map(MyClass::getStr)
  .collect(Collectors.toSet());

// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
  .filter(e -> unavailableItems.contains(e))
  .collect(Collectors.toList());

Tags:

Java

Filter