Java 8 convert Map> to Map>

前端 未结 1 376
生来不讨喜
生来不讨喜 2020-12-31 17:54

I need to convert Map> to Map>. I\'ve been struggling with this issue for some time.

It\'s ob

相关标签:
1条回答
  • 2020-12-31 18:47

    I think you were close, you would need to flatMap those entries to a Stream and collect from there. I've used the already present SimpleEntry, but you can use a Pair of some kind too.

    initialMap.entrySet()
              .stream()
              .flatMap(entry -> entry.getValue().stream().map(v -> new SimpleEntry<>(entry.getKey(), v)))
              .collect(Collectors.groupingBy(
                   Entry::getValue,
                   Collectors.mapping(Entry::getKey, Collectors.toList())
             ));
    

    Well, if you don't want to create the extra overhead of those SimpleEntry instances, you could do it a bit different:

        Map<Integer, List<String>> result = new HashMap<>();
    
        initialMap.forEach((key, values) -> {
            values.forEach(value -> result.computeIfAbsent(value, x -> new ArrayList<>()).add(key));
        });
    
    0 讨论(0)
提交回复
热议问题