map用value值找key的两种方法

map用value值找key的两种方法

Map中是一个key有且只有一个value. 但是一个value可以对应多个key值.
只用用特殊方法才能用value值来找key,以下就是用value值找key的两种方法

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Map<Integer,Integer> m=new HashMap<>();
    m.put(1, 2);
    m.put(2, 2);
    m.put(3, 0);
    m.put(4, 1);
    Collection<Integer> c=m.values();
    Integer sum=0;
    for(Integer b:c){
        if(sum.compareTo(b)<0){
            sum=b;
        }
    }
    //      Set<Entry<Integer,Integer>> sets=m.entrySet();
    //      for(Entry<Integer,Integer> e:sets){
    //          if(sum.compareTo(e.getValue())==0){
    //              System.out.println(e.getKey());
    //          }
    //      }
    Set en=m.entrySet();
    Iterator it=en.iterator();
    while(it.hasNext()){
        Map.Entry me=(Map.Entry) it.next();
        //entrySet()方法就是把map中的每个键值对变成对应成Set集合中的一个对象.
        if(me.getValue().equals(sum)){
            //这里的Map.Entry就是一种类型,专值map中的一个键值对组成的对象.
            System.out.println(me.getKey()+":"+me.getValue());
        }
    } 

猜你喜欢

转载自blog.csdn.net/TomLoveJerry1/article/details/82527471
今日推荐