Peek 中的 Java 8 条件逻辑?

我目前有一些 Java 8 代码,如下所示 - 非常确定我可以将其合并到单个调用中,但不确定如何在 Looped 映射中将条件调用到位。可以用 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() ) );

下一位根据键的 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.. )


拉丁的传说
浏览 61回答 1
1回答

慕村9548890

您似乎正在寻找的是一个条件groupingBy:Map<String, List<LeadChannel>> finalMap = groups&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(channel ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; channel.getResolution().getId().equals(RESOLVED_STATUS) ?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "unresolved" : "resolved"));或者在多个管道中,了解如何对数据进行分区,然后根据问题中共享的条件进一步映射它:Map<Boolean, List<LeadChannel>> mappedUp = groups&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.partitioningBy(channel ->&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; channel.getResolution().getId().equals(RESOLVED_STATUS)));Map<String, List<LeadChannel>> finalMap = mappedUp.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; // in a similar manner you can map your current map's entries as well&nbsp; &nbsp; &nbsp; &nbsp; .map(e -> new AbstractMap.SimpleEntry<>(e.getKey() ? "resolved" : "unresolved", e.getValue()))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));或者正如 Holger 建议的那样,最好使用 lambda 直接收集为Map<String, List<LeadChannel>> finalMap = mappedUp.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(e -> e.getKey()? "resolved": "unresolved", Map.Entry::getValue))&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java