Is there a more elegant/built-in way to reverse the keys and values of a Hashmap?
I currently have the following.
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;
}
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;
}
Or more generally:
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;
}
I'd do something similar (but if you must do this kind of thing frequently, consider Guava), only replacing the List with Set (seems a little more consistent) and prefilling the reversemap:
private Map<Boolean, Set<String>> reverseMap(Map<String, Boolean> permissions) {
Map<Boolean, Set<String>> returnvalue = new HashMap<Boolean, Set<String>>();
returnvalue.put(Boolean.TRUE, new HashSet<String>());
returnvalue.put(Boolean.FALSE, new HashSet<String>());
for (Entry<String, Boolean> entry : permissions.entrySet())
returnvalue.get(entry.getValue()).add(entry.getKey());
return returnvalue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With