Map集合的遍历之键值对对象找键和值

Map集合的遍历之键值对对象找键和值

**注意:**Map是无顺序的,所以输出结果是无序的

import java.util.Set;

/*Map集合的遍历之键值对对象找键和值 注意:Map是无顺序的,所以输出结果是无序的*/
public class Demo1_map {
    public static void main(String[] args) {
        HashMap <String, Integer> hm = new HashMap <> ( );
        hm.put ("张三" , 23);
        hm.put ("张四" , 24);
        hm.put ("张五" , 25);
        /*Set <Map.Entry<String,Integer>> entrySet = hm.entrySet ();  //获取所有的键值对象的集合
        Iterator<Map.Entry <String,Integer>> it = entrySet.iterator ();   //获取迭代器)
      while (it.hasNext ()){
            Map.Entry <String,Integer> en = it.next ();  //获取键值对对象
            String key = en.getKey ();  //根据键值对对象获取键
            Integer value = en.getValue (); //根据键值对对象获取值
            System.out.println (key + "=" + value);
        } */
        for (Map.Entry <String, Integer> en : hm.entrySet ( )) {    //开发常用的方法,提高效率
            System.out.println (en.getKey ( ) + "=" + en.getValue ( ));

        }

    }
}
结果
张四=24
张三=23
张五=25

发布了55 篇原创文章 · 获赞 5 · 访问量 4170

猜你喜欢

转载自blog.csdn.net/qq_43654669/article/details/100161674