总结
筛选一个字符串列表,查找那些(a)包含单词“Nursing”,并且(b)同时包含单词“Specialist”或“Coordinator”的字符串。
Stream.of (
"Nursing Professional Development Specialist", // 匹配项
"Accountant", // 不匹配项
"Nursing Manager", // 不匹配项
"Nursing Resource Coordinator" // 匹配项
)
.filter (
( String job ) ->
Arrays.stream(job.split(" ")).anyMatch(Set.of("Nursing")::contains) &&
Arrays.stream(job.split(" ")).anyMatch(Set.of("Specialist", "Coordinator")::contains)
)
.toList();
输出结果为:[Nursing Professional Development Specialist, Nursing Resource Coordinator]
流过滤操作
可以将每个职位标题中的单词转换成一个流。使用String#split
方法会生成一个数组,将该数组传递给Arrays.stream
就可以得到一个字符串流,即职位标题中的单词流。
Arrays.stream(job.split(" "))
示例数据:
List<String> jobs = List.of(
"Nursing Professional Development Specialist", // 匹配项
"Accountant", // 不匹配项
"Nursing Manager", // 不匹配项
"Nursing Resource Coordinator" // 匹配项
);
定义目标关键词集合:
Set<String> x = Set.of("Nursing");
Set<String> y = Set.of("Specialist", "Coordinator");
在职位标题的流上应用这些目标关键词集合作为过滤器的谓词,并收集通过测试的职位标题。
List<String> hits = jobs.stream()
.filter((String job) ->
Arrays.stream(job.split(" ")).anyMatch(x::contains))
.filter((String job) ->
Arrays.stream(job.split(" ")).anyMatch(y::contains))
.toList();
打印到控制台:
System.out.println("hits = " + hits);
输出结果为:hits = [Nursing Professional Development Specialist, Nursing Resource Coordinator]
我们也可以组合我们的谓词语句测试。但我可能更倾向于使用两个单独的filter
调用的原始长版本。
List<String> hits = jobs.stream()
.filter((String job) ->
Arrays.stream(job.split(" ")).anyMatch(x::contains) &&
Arrays.stream(job.split(" ")).anyMatch(y::contains)
)
.toList();