I have a hashmap as below:
1->x
2->y
3->x
4->z
Now i want to know all keys whose value is x (ans: [1,3] ). what is best way to do?
Brute force way is to just iterate over map and store all keys in array whose value is x.
Is there any efficient way for this.
Thanks
解决方案
You can use a MultiMap to easily get all those duplicate values.
Map map = new HashMap();
map.put(1, "x");
map.put(2, "y");
map.put(2, "z");
map.put(3, "x");
map.put(4, "y");
map.put(5, "z");
map.put(6, "x");
map.put(7, "y");
System.out.println("Original map: " + map);
Multimap multiMap = HashMultimap.create();
for (Entry entry : map.entrySet()) {
multiMap.put(entry.getValue(), entry.getKey());
}
System.out.println();
for (Entry> entry : multiMap.asMap().entrySet()) {
System.out.println("Original value: " + entry.getKey() + " was mapped to keys: "
+ entry.getValue());
}
Prints out:
Original map: {1=x, 2=z, 3=x, 4=y, 5=z, 6=x, 7=y}
Original value: z was mapped to keys: [2, 5]
Original value: y was mapped to keys: [4, 7]
Original value: x was mapped to keys: [1, 3, 6]
Per @noahz's suggestion, forMap and invertFrom takes fewer lines, but is arguably more complex to read:
HashMultimap multiMap =
Multimaps.invertFrom(Multimaps.forMap(map),
HashMultimap. create());
in place of:
Multimap multiMap = HashMultimap.create();
for (Entry entry : map.entrySet()) {
multiMap.put(entry.getValue(), entry.getKey());
}