gpt4 book ai didi

Peek 中的 Java 8 条件逻辑?

转载 作者:行者123 更新时间:2023-11-30 05:26:12 25 4
gpt4 key购买 nike

我目前有一些 Java 8 代码,如下所示 - 非常确定我可以将其合并到单个调用中,但不确定如何在循环映射内放置我的条件调用。可以用 peek() 来做到这一点吗?或者其他 Java 8 调用?

当前代码

//turn above groups into a map, grouped by Resolution
Map<Long,List<LeadChannel>> mappedUp = groups
.stream()
.collect( Collectors.groupingBy( channel->channel.getResolution().getId() ) );

下一位根据 key 的 ID 手动转换为字符串映射。

Map<String, List<LeadChannel>> finalMap = new HashMap<String, List<LeadChannel>>();

for ( Map.Entry<Long,List<LeadChannel>> entry : mappedUp.entrySet()) {
if( !entry.getKey().equals( RESOLVED_STATUS ) ) {
finalMap.put( "unresolved", entry.getValue() );
} else {
finalMap.put( "resolved", entry.getValue() );
}
}

我正在尝试这样做:

 Map<String,List<LeadChannel>> mappedUp = groups
.stream()
.collect( Collectors.groupingBy( channel->channel.getResolution().getId() ) )
.entrySet()
.stream()
.peek( if statement etc.. )

最佳答案

您似乎正在寻找的是条件groupingBy:

Map<String, List<LeadChannel>> finalMap = groups
.stream()
.collect(Collectors.groupingBy(channel ->
channel.getResolution().getId().equals(RESOLVED_STATUS) ?
"unresolved" : "resolved"));

或者在多个管道中,了解如何对数据进行分区,然后根据问题中共享的条件进一步映射它:

Map<Boolean, List<LeadChannel>> mappedUp = groups
.stream()
.collect(Collectors.partitioningBy(channel ->
channel.getResolution().getId().equals(RESOLVED_STATUS)));

Map<String, List<LeadChannel>> finalMap = mappedUp.entrySet().stream()
// in a similar manner you can map your current map's entries as well
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey() ? "resolved" : "unresolved", e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

或者按照 Holger 的建议,最好使用 lambda 直接收集为

Map<String, List<LeadChannel>> finalMap = mappedUp.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey()? "resolved": "unresolved", Map.Entry::getValue))

关于Peek 中的 Java 8 条件逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545220/

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