zoukankan      html  css  js  c++  java
  • java集合使用——HashMap

    在map中插入、删除和定位元素时,HashMap是最好的选择。如果要按照自然顺序或自定义顺序遍历(获取所有元素),那么treemap更好一些。

    第一:构造和添加元素

    HashMap map = new HashMap();
      map.put("1001", "zhangsan");
      map.put("1002", "lisi");
      map.put("1003", "wanger");

    第二:获得某一个元素

    map.get("1002").toString(); //1002是key

    第三:遍历(获取所有元素)

    思路一:读出集合中的所有关键字,根据关键字依次查找相应的值

    Set keys = map.keySet(); //获得所有关键字集合
      Iterator it = keys.iterator(); //遍历关键字集合
      while(it.hasNext()){
       String str = map.get(it.next()).toString(); //通过关键字查找元素
       System.out.println(str);
      }

    思路二:将map的key和value看成是一个对象的两个属性

    Set keys = map.entrySet(); //获得key 和 value 集合
      Iterator it = keys.iterator(); 

      while(it.hasNext()){
       Map.Entry e = (Map.Entry)it.next();
       System.out.println("key"+e.getKey()+"value"+e.getValue());
      }

  • 相关阅读:
    Python Day14
    Python Day13
    Python Day12
    Python Day11
    Python Day10
    Python Day9
    Python Day8
    Python Day7
    Python Day6
    Python Day5
  • 原文地址:https://www.cnblogs.com/suinuaner/p/javaset_hashmap.html
Copyright © 2011-2022 走看看