gpt4 book ai didi

java - 'filter()' and ' map()'可以交换

转载 作者:行者123 更新时间:2023-12-03 20:23:08 28 4
gpt4 key购买 nike

我有一个简单的流,如下所示:

List<Long> r = l.stream()
.filter(a->a.getB() % 2 == 0)
.map(A::getB)
.collect(Collectors.toList());
但 Intellij 建议我:

'filter()' and 'map()' can be swappedInspection info: Reports stream API call chains which can be simplified. It allows to avoid creating redundant temporary objects when traversing a collection. e.g.

  • collection.stream().forEach() → collection.forEach()
  • collection.stream().collect(toList/toSet/toCollection()) → new CollectionType<>(collection)

Intellij给出的例子很容易理解,但我不明白为什么它建议我 map().filter() .
我查看来源 ReferencePipeline但找不到任何线索: map().filter()filter().map()对于与流实现相关的临时对象没有任何区别(如果 filter().map() 是一个让我更加困惑的原语,则 A.b 将具有较少的自动装箱)。
那么,我是否缺少流实现的某些点,或者这是 Intellij 的误报?

最佳答案

a.getB()被调用两次 - 一次在过滤器内部,它也是映射函数,所以不要这样做两次,最好先使用 getB 映射它。然后过滤掉List<Long> r = l.stream().map(A::getB).filter(b->b % 2 == 0).collect(Collectors.toList()); 编辑
getB返回 long然后 mapToLong可用于避免中间装箱操作。

List<Long> r = l.stream()
.mapToLong(A::getB)
.filter(b->b % 2 == 0)
.boxed()
.collect(Collectors.toList());
sample 输出
使用静态计数器计算 get 方法的调用:
class A {
public static int count = 0;
private long b;

public long getB() {
count++;
return b;
}
}
List<A> list= List.of(new A(1L), new A(3L), new A(4L));
list.stream() 
.filter(a -> a.getB()%2 == 0)
.map(A::getB)
.collect(Collectors.toList());
System.out.println(A.count); // returns 4
然而
list.stream()
.mapToLong(A::getB)
.filter(b->b % 2 == 0)
.boxed()
.collect(Collectors.toList());
System.out.println(A.count); // returns 3

关于java - 'filter()' and ' map()'可以交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66979712/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com