gpt4 book ai didi

java - 在原始流上使用收集器

转载 作者:搜寻专家 更新时间:2023-11-01 02:45:56 25 4
gpt4 key购买 nike

在 Java 8 中有没有使用 Stream::collect(Collector) 的方式?在原始流上?

通常是 Stream<Integer>例如有两种收集方法:

但是IntStream只有一种收集方法:

现在作为示例代码,我有以下内容:

@Override
public void run() {
result = LongStream.range(1, maximum).boxed()
.collect(Collectors.toMap(i -> i, i -> (int)Iterators.longStream(new CollatzGenerator(i)).count()))
.entrySet().stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get().getKey();
}

如您所见,我首先将基元装箱以便能够使用 Collectors.方法。

有什么方法可以让我使用原语并仍然拥有与 Collectors.toMap 相同的代码吗??

最佳答案

因为 Map 是一个通用接口(interface),所以没有装箱就无法创建 Map。但是,当您只想创建另一个流(只有两个值包装在 Map.Entry 中时,将项目收集到 Map 中根本没有意义).您可以只创建 Map.Entry 实例而不收集值:

LongStream.range(1, maximum)
.mapToObj(i->new AbstractMap.SimpleEntry<>(i, Iterators.longStream(new CollatzGenerator(i)).count()))
.max(Comparator.comparingLong(Map.Entry::getValue))
.get().getKey();

这仍然会进行自动装箱,但是一旦到了这一点,您也可以通过自己创建一个适当的值持有者类来摆脱 Map.Entry:

static final class TwoLongs {
final long key, value;
TwoLongs(long k, long v) { key=k; value=v; }
public long getKey() { return key; }
public long getValue() { return value; }
}

有了这个 holder 类,您就可以处理您的数据,而无需装箱 long:

LongStream.range(1, maximum)
.mapToObj(i->new TwoLongs(i, Iterators.longStream(new CollatzGenerator(i)).count()))
.max(Comparator.comparingLong(TwoLongs::getValue))
.get().getKey();

嗯,它仍然是某种装箱,但创建一个项目(TwoLongs 实例)对象而不是三个(一个 Map.Entry 和两个 Long s).

关于java - 在原始流上使用收集器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22022359/

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