Reversing a HashMap from Map to Map>

后端 未结 4 1139
遥遥无期
遥遥无期 2021-01-19 04:11

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

I currently have the following.

private Map

        
4条回答
  •  温柔的废话
    2021-01-19 04:37

    First thing to note is that you don't really need a reverse map if your values are only true or false. It will make sense if you have a broader range of values.

    One easy (but not very elegant) way to get the entries with a specific value is:

    public static  Set getKeysByValue(Map map, E value) {
         Set keys = new HashSet();
         for (Entry entry : map.entrySet()) {
             if (entry.getValue().equals(value)) {
                 keys.add(entry.getKey());
             }
         }
         return keys;
    }
    

    You can see that this is not so good if you need to call it every now and then. It makes sense to have two different maps (straight and reverse) and add entries to both. You can't use Bidi maps since there is no 1:1 relation between keys and values.

    UPDATE: The following solution won't work. See comments. You can also consider using a TreeMap and keep it sorted based on the value. This way you can have a sorted set by calling map.entrySet() any time (denies entries first, then allows). The drawback is that it is only one set.

    ValueComparator bvc =  new ValueComparator(map);
    TreeMap sorted_map = new TreeMap(bvc);
    
    class ValueComparator implements Comparator {
      Map base;
    
      public ValueComparator(Map base) {
          this.base = base;
      }
    
      public int compare(Object a, Object b) {
        return (Boolean)base.get(a).compareTo((Boolean)base.get(b));
      }
    }
    

提交回复
热议问题