gpt4 book ai didi

java - 从单个流中收集更多列表,然后将它们全部合并

转载 作者:行者123 更新时间:2023-11-29 08:28:58 26 4
gpt4 key购买 nike

是否有更优雅的方式从单个流中收集更多列表,然后将它们全部合并?

这是我想出的:

    private Set<Long> getAllIds(List<MyClass> fetchedElements) {
Set<Long> myIds = new HashSet<>();
myIds.addAll(fetchedItems.stream().map(MyClass::getBlueId).collect(Collectors.toList()));
myIds.addAll(fetchedItems.stream().map(MyClass::getRedId).collect(Collectors.toList()));
myIds.addAll(fetchedItems.stream().map(MyClass::getGreenId).collect(Collectors.toList()));
return myIds;
}

当我查看这三行代码时,我觉得那里存在代码重复,但我没有找到一种方法来加入我正在对流执行的不同 map 操作。

感谢您的帮助!

最佳答案

使用flatMap!!

fetchedElements.stream()
.flatMap(item -> Stream.of(item.getBlueId(), item.getRedId(), item.getGreenId()))
.collect(Collectors.toSet());

请注意,评估顺序是 BRGBRG 而不是 BBRRGG,输出顺序当然是未定义的,因为您使用的是 Set。我认为这无关紧要。


您可以使此方法更通用:

private Set<Long> getAllIds(List<MyClass> fetchedElements,
List<Function<MyClass, Long>> extractors) {
return fetchedElements.stream()
.flatMap(item -> extractors.stream().map(f -> f.apply(item)))
.collect(Collectors.toSet());
}

调用:

 Set<Long> myIds = getAllIds(fetchedElements, List.of(MyClass::getBlueId, MyClass::getRedId, MyClass::getGreenId))

如果你想要其他评估顺序,交换操作顺序:

extractors.stream()
.flatMap(f -> fetchedElements.stream().map(item -> f.apply(item))
.collect(Collectors.toSet()));

关于java - 从单个流中收集更多列表,然后将它们全部合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893029/

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