假设我有一个字符串列表,我想通过过滤字符串列表来过滤它们。 对于包含以下内容的列表: "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());
除了扩展 lambda 表达式的主体并编写一个带有标志的函数来检查每个过滤器之外,还有其他方法可以做到这一点吗?
最佳答案
您应该改为对要匹配的列表执行 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());
关于过滤器的java流列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54767135/