2016-7-20 getKeyByValue in Map
Map中通过KEY获取VALUE是很容易,但是通过VALUE来获取KEY,则可能得到多个相同VALUE的KEY,所以Map本身并没有其对应的函数.
public class MapUtils { private static Map<Integer, Object> map = null; public static Map<Integer, Object> setMap(Map<Integer, Object> _map) { return map = _map; } public static Object getKeyByValue(Object value) { Object o = null; ArrayList<Object> matchList = new ArrayList<Object>(); // 声明顺序表来存放符合条件的KEY /* * 这里关键是: * entrySet() : 它返回一个包含Map.Entry集的Set对象. * Map.Entry对象有getValue和getKey的方法,利用这两个方法就可以达到从值取键的目的了 **/ Set<?> set = map.entrySet(); Iterator<?> it = set.iterator(); while (it.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) it.next(); if (entry.getValue().equals(value)) { o = entry.getKey(); matchList.add(o); // 把符合条件的KEY先放到容器中 } } return matchList; } }
调用:
import java.util.*; class Elemt { public int a; String b = ""; public Elemt(int a, String string) { this.a = a; b = string; } public Object findElem() { return MapUtils.getKeyByValue(this); } } public class test_find_Key { public static void main(String[] args) { Map<Integer, Object> map = new HashMap<>(); Elemt e1 = new Elemt(1, "1"); Elemt e2 = new Elemt(1, "1"); Elemt e3 = new Elemt(1, "1"); Elemt e4 = e3; map.put(6, e1); map.put(7, e2); map.put(8, e3); MapUtils.setMap(map); @SuppressWarnings("unchecked") ArrayList<Object> list = (ArrayList<Object>)e4.findElem(); for (Object object : list) { System.out.println(object); } } }
结果: