java的map是常用的数据结构,在使用中一般使用key去访问value,但是有时候也会碰到需要用value的值来找到对应的key的情况。
由于map的key是唯一的,所以用key->value不会产生歧义,但是value的值可能会重复,因此通过value来返回key的话会可能会匹配到多个key值,这里我们只考虑使用迭代的方法返回第一个匹配的key值。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by Yangyang Deng on 17-7-19.
*/
public class test {
public static void main(String args[]) {
Map<Integer,String> map = new HashMap<Integer, String>();
String[] fruits = {"apple","banana","orange","watermelon","pear"};
for(int i=0;i<fruits.length;i++) {
map.put(i,fruits[i]);
}
getKeysAndValues(map);
getKeyByValue(map,"watermelon");
}
// 遍历map的所有key和value
public static void getKeysAndValues(Map map) {
Iterator it = map.entrySet().iterator();
Map.Entry entry = null;
while (it.hasNext()) {
// 将迭代器it转换成 Map.Entry的目的是方便得到key和value
entry = (Map.Entry) it.next();
System.out.println(entry.getKey()+"->"+entry.getValue());
}
}
// 通过map的value得到key
public static void getKeyByValue(Map map, Object value) {
// 首先得到entrySet的迭代器it
Iterator it = map.entrySet().iterator();
Map.Entry entry = null;
while (it.hasNext()) {
// 这里注意用it.next的到entry,并且it会在执行it.next()之后自动后移一位;
// 访问第一个entry也要使用it.next(),不能直接用it;
entry = (Map.Entry) it.next();
Object obj = entry.getValue();
if (value.equals(obj)) {
break;
}
}
System.out.println(entry.getValue()+"->"+entry.getKey());
}
}