从 Map<String, Boolean> 反转 HashMap映射<布尔,列表<字符串>> [英] Reversing a HashMap from Map&lt;String, Boolean&gt; to Map&lt;Boolean, List&lt;String&gt;&gt;

查看:36
本文介绍了从 Map<String, Boolean> 反转 HashMap映射<布尔,列表<字符串>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更优雅/内置的方式来反转 Hashmap 的键和值?

Is there a more elegant/built-in way to reverse the keys and values of a Hashmap?

我目前有以下内容.

private Map<Boolean, List<String>> reverseMap(Map<String, Boolean> permissions) {
    List<String> allow = new ArrayList<String>();
    List<String> deny = new ArrayList<String>();
    Map<Boolean, List<String>> returnvalue = new HashMap<Boolean, List<String>>();

    for (Entry<String, Boolean> entry : permissions.entrySet()) {
        if(entry.getValue()) {
            allow.add(entry.getKey());
        } else {
            deny.add(entry.getKey());
        }
    }

    returnvalue.put(true, allow);
    returnvalue.put(false, deny);
    return returnvalue;
}

推荐答案

您可以考虑使用 GuavaMultimap 实现.例如:

You might consider using one of Guava's Multimap implementations. For example:

private Multimap<Boolean, String> reverseMap(Map<String, Boolean> permissions) {
   Multimap<Boolean, String> multimap = ArrayListMultimap.create();
   for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
      multimap.put(entry.getValue(), entry.getKey());
   }
   return multimap;
}

或更一般地说:

private static <K, V> Multimap<V, K> reverseMap(Map<K, V> source) {
   Multimap<V, K> multimap = ArrayListMultimap.create();
   for (Map.Entry<K, V> entry : source.entrySet()) {
      multimap.put(entry.getValue(), entry.getKey());
   }
   return multimap;
}

这篇关于从 Map<String, Boolean> 反转 HashMap映射<布尔,列表<字符串>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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