在带有过滤条件的 Java 8 流中,集合中的每个元素都被传递给过滤器以检查条件。在这里,我正在编写两种不同的过滤条件并给出不同的工作流程。
public static void main(String[] args) {
List<String> asList = Arrays.asList("a", "b", "c", "d", "e", "a", "b", "c");
//line 1
asList.stream().map(s -> s).filter(distinctByKey(String::toString)).forEach(System.out::println);
Predicate<String> strPredicate = (a) -> {
System.out.println("inside strPredicate method--");
return a.startsWith("a");
};
//line 2
asList.stream().filter(strPredicate).forEach(System.out::println);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
System.out.println("inside distinctByKey method...");
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
在上面的示例代码中,语句第 1 行过滤条件只执行一次,但第 2 行正在为集合输出中的每个元素执行。
我认为该distinctByKey方法会为集合中的每个元素执行,但事实并非如此。为什么 ?
另外,Set对象引用变量seen是仅执行一次?流量如何运作?
千巷猫影
芜湖不芜
相关分类