java流过滤器列表

ste*_*337 3 java filter java-stream

假设我有一个字符串列表,我想通过过滤字符串列表过滤它们.对于包含以下内容的列表:"abcd","xcfg","dfbf"

我会精确列出过滤字符串:"a","b",以及像filter之后的东西(i-> i.contains(filterStrings)我想收到"abcd","dfbf"的列表,以及列表过滤字符串:"c","f"我想要列出"xcfg"和"dfbf"的列表.

List<String> filteredStrings = filteredStrings.stream()
            .filter(i -> i.contains("c") || i.contains("f")) //i want to pass a list of filters here
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

有没有其他方法这样做而不是扩展lambda表达式的主体和编写一个带有标志的函数来检查每个过滤器?

Nam*_*man 5

您应该anyMatch在列表上执行以匹配:

List<String> input = Arrays.asList("abcd", "xcfg", "dfbf"); // your input list
Set<String> match = new HashSet<>(Arrays.asList("c", "f")); // to match from
List<String> filteredStrings = input.stream()
        .filter(o -> match.stream().anyMatch(o::contains))
        .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)