Java-8:Stream如何在Map< K,List< D>>上转换?映射< D,列表< K>> [英] Java-8: Stream How to convert on Map<K, List<D>> to Map<D, List<K>>

查看:142
本文介绍了Java-8:Stream如何在Map< K,List< D>>上转换?映射< D,列表< K>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究Java 8并试用lambdas,我有一个用于上述问题的用例,我使用通常的for循环来解决这个问题非常冗长且难以阅读

I've just started looking at Java 8 and to try out lambdas, I have an use case for the above problem, which I am solving using the usual for loop which is very lengthy and hard to read

我的现有代码

private static Map<DataType, List<OperatorType>> buildmap() {

    Map<DataType, List<OperatorType>> map = Maps.newHashMap();

    for (OperatorType type : OperatorType.values()) {
        List<DataType> supportedTypes = type.getSupportedtypes();
        supportedTypes.forEach(datatype -> {
            if (map.containsKey(datatype)) {
                List<OperatorType> list = map.get(datatype);
                list.add(type);
                map.put(datatype,
                        list);
            } else {
                map.put(datatype,
                        new ArrayList<OperatorType>() {
                            private static final long serialVersionUID = 1L;

                            {
                                add(type);
                            }
                        });
            }
        });
    }

    return Collections.unmodifiableMap(new LinkedHashMap<>(map));
}


推荐答案

也许这样的事情会有所帮助:

Maybe something like this helps:

<D, K> Map<D, List<K>> swap(Map<K, List<D>> map) {
  return map.entrySet().stream()
                       .flatMap(e -> e.getValue().stream()
                                                 .map(v -> new SimpleEntry<>(v, e.getKey())))
     .collect(Collectors.groupingBy(Entry::getKey, 
                                    Collectors.mapping(Entry::getValue,
                                                       Collectors.toList())));
}

Streams并不总是解决各种问题的最简单方法。请参阅 @Flown的回答,以获得更易理解且更简单的非流式解决方案。

Streams are not always the easiest solution to all kinds of problems. See @Flown's answer for a more understandable and easy non-stream solution.

您可以使用 .forEach 编写Flown的答案Stream-like,但它实际上并没有更具可读性(假设 values() getSupportedTypes()都返回 List )我不会推荐它只是说你正在使用流:

You could write Flown's answer also "Stream-like" by using .forEach, but it doesn't really get more readable (assuming values() and getSupportedTypes() both return a List) and I wouldn't recommend it just to say that you are using streams:

OperatorType.values()
  .forEach(type -> type.getSupportedTypes()
    .forEach(dataType -> map.computeIfAbsent(dataType, dt -> new ArrayList<>())
                                                .add(type)));

这篇关于Java-8:Stream如何在Map&lt; K,List&lt; D&gt;&gt;上转换?映射&lt; D,列表&lt; K&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆