Map依据值获取key,找到一篇大佬的文章,本文是CV过去的,
原文:https://www.techiedelight.com...
1.entrySet() 办法
import java.util.HashMap;import java.util.Map; class Main{ public static <K, V> K getKey(Map<K, V> map, V value) { for (Map.Entry<K, V> entry: map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; } // Java8 public static <K, V> K getKey(Map<K, V> map, V value) { return map.entrySet().stream() .filter(entry -> value.equals(entry.getValue())) .findFirst().map(Map.Entry::getKey) .orElse(null); } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); System.out.println(getKey(hashMap, 2)); // prints `B` }}
2.keySet() 办法
import java.util.HashMap;import java.util.Map; class Main{ public static <K, V> K getKey(Map<K, V> map, V value) { for (K key: map.keySet()) { if (value.equals(map.get(key))) { return key; } } return null; } // Java8 public static <K, V> K getKey(Map<K, V> map, V value) { return map.keySet() .stream() .filter(key -> value.equals(map.get(key))) .findFirst().get(); } public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); System.out.println(getKey(hashMap, 2)); // prints `B` }}
3.反转Map
import java.util.HashMap;import java.util.Map; class MyHashMap<K, V> extends HashMap<K, V>{ Map<V, K> reverseMap = new HashMap<>(); @Override public V put(K key, V value) { reverseMap.put(value, key); return super.put(key, value); } public K getKey(V value) { return reverseMap.get(value); } } class Main{ public static void main(String[] args) { MyHashMap<String, Integer> hashMap = new MyHashMap(); hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); System.out.println(hashMap.getKey(2)); // prints `B` }}
4.Guava’s BiMap类
import com.google.common.collect.BiMap;import com.google.common.collect.ImmutableBiMap; class Main{ public static <K, V> K getKey(BiMap<K, V> map, V value) { return map.inverse().get(value); } public static void main(String[] args) { BiMap<String, Integer> bimap = ImmutableBiMap.of("A", 1, "B", 2, "C", 3); System.out.println(getKey(bimap, 2)); // prints `B` }}
5.Apache Commons Collections
import org.apache.commons.collections4.BidiMap;import org.apache.commons.collections4.bidimap.DualHashBidiMap; class Main{ public static <K, V> K getKey(BidiMap<K, V> map, V value) { return map.inverseBidiMap().get(value); } public static void main(String[] args) { BidiMap<String, Integer> bimap = new DualHashBidiMap<>(); bimap.put("A", 1); bimap.put("B", 2); bimap.put("C", 3); System.out.println(getKey(bimap, 2)); // prints `B` }}
原文:https://www.techiedelight.com...