使用流内的流检查进行过滤

时间:2017-11-09 04:26:18

标签: java java-8

以下程序仍会打印frank, jake, justinpersie,因为列入黑名单,其中不应包含justin

List<String> blacklists = new ArrayList<>(Arrays.asList("mike", "ryan", "carl", "justin"));
List<String> names = new ArrayList<>(Arrays.asList("frank", "jake", "justin", "persie"));

List<String> validatedNames = names.stream()
        .filter(name ->
            blacklists.stream()
                    .anyMatch(blacklist -> !blacklist.equals(name))
        )
        .collect(Collectors.toList());

validatedNames.forEach(name -> System.out.println(name));

1 个答案:

答案 0 :(得分:3)

错误就在这一行:

.anyMatch(blacklist -> !blacklist.equals(name))

每个名字在blacklists都有一些不匹配的项目,因此它们都会通过。您需要像这样反转条件:

.noneMatch(blacklist -> blacklist.equals(name))

但整个内心流真的没必要。只需使用List.contains()

List<String> validatedNames = names.stream()
        .filter(name -> !blacklists.contains(name))
        .collect(Collectors.toList());

如果您愿意修改names,则可以完全跳过该流:

names.removeAll(blacklists);