iterating and filtering two lists using java 8

后端 未结 9 494
抹茶落季
抹茶落季 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<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());
    
    0 讨论(0)
  • 2020-12-09 17:58

    this can be achieved using below...

     List<String> unavailable = list1.stream()
                                .filter(e -> !list2.contains(e))
                                .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-09 18:05

    if you have class with id and you want to filter by id

    line1 : you mape all the id

    line2: filter what is not exist in the map

    Set<String> mapId = entityResponse.getEntities().stream().map(Entity::getId).collect(Collectors.toSet());
    
    List<String> entityNotExist = entityValues.stream().filter(n -> !mapId.contains(n.getId())).map(DTOEntity::getId).collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题