当前位置: 移动技术网 > IT编程>开发语言>Java > Map集合的四种遍历方式代码示例

Map集合的四种遍历方式代码示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

很久以前写的代码,和上一个做比较吧!便于以后查看。

import java.util.hashmap;
import java.util.iterator;
import java.util.map;
public class testmap {
  public static void main(string[] args) {
    map<integer, string> map = new hashmap<integer, string>();
    map.put(1, "a");
    map.put(2, "b");
    map.put(3, "ab");
    map.put(4, "ab");
    map.put(4, "ab");// 和上面相同 , 会自己筛选
    system.out.println(map.size());
    // 第一种:
    /*
     * set<integer> set = map.keyset(); //得到所有key的集合
     * 
     * for (integer in : set) { string str = map.get(in);
     * system.out.println(in + "   " + str); }
     */
    system.out.println("第一种:通过map.keyset遍历key和value:");
    for (integer in : map.keyset()) {
      //map.keyset()返回的是所有key的值
      string str = map.get(in);//得到每个key多对用value的值
      system.out.println(in + "   " + str);
    }
    // 第二种:
    system.out.println("第二种:通过map.entryset使用iterator遍历key和value:");
    iterator<map.entry<integer, string>> it = map.entryset().iterator();
    while (it.hasnext()) {
       map.entry<integer, string> entry = it.next();
        system.out.println("key= " + entry.getkey() + " and value= " + entry.getvalue());
    }
    // 第三种:推荐,尤其是容量大时
    system.out.println("第三种:通过map.entryset遍历key和value");
    for (map.entry<integer, string> entry : map.entryset()) {
      //map.entry<integer,string> 映射项(键-值对) 有几个方法:用上面的名字entry
      //entry.getkey() ;entry.getvalue(); entry.setvalue();
      //map.entryset() 返回此映射中包含的映射关系的 set视图。
      system.out.println("key= " + entry.getkey() + " and value= "
          + entry.getvalue());
    }
    // 第四种:
    system.out.println("第四种:通过map.values()遍历所有的value,但不能遍历key");
    for (string v : map.values()) {
      system.out.println("value= " + v);
    }
  }
}

结果:

4
第一种:通过map.keyset遍历key和value:
1   a
2   b
3   ab
4   ab
第二种:通过map.entryset使用iterator遍历key和value:
key= 1 and value= a
key= 2 and value= b
key= 3 and value= ab
key= 4 and value= ab
第三种:通过map.entryset遍历key和value
key= 1 and value= a
key= 2 and value= b
key= 3 and value= ab
key= 4 and value= ab
第四种:通过map.values()遍历所有的value,但不能遍历key
value= a
value= b
value= ab
value= ab

总结

以上就是本文关于map集合的四种遍历方式代码示例的全部内容,希望对大家有所帮助。温故而知新,可以为师矣。。。map集合的遍历属于老话题了,有什么问题直接留言吧,小编会及时回复大家的。感兴趣的朋友可以继续参阅:java中map遍历方式的选择问题详解struts2中ognl遍历数组,list和map方法详解java map存放数组并取出值代码详解等,感谢朋友们对本站的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网