当前位置:   article > 正文

HashMap的遍历方式_android hashmap遍历

android hashmap遍历

1、遍历Key

System.out.println("遍历 key:");
for(String key : map.keySet()){
    System.out.println(key + ":" + map.get(key));
}
  • 1
  • 2
  • 3
  • 4

2、遍历value

System.out.println("遍历 value:");
for(Object value : map.values()){
    System.out.println(value.toString());
}
  • 1
  • 2
  • 3
  • 4

3、遍历entry

System.out.println("遍历 entry:");
for(Map.Entry<String, Object> obj : map.entrySet()){
    System.out.println(obj.getKey() + ":" + obj.getValue());
}
  • 1
  • 2
  • 3
  • 4

4、迭代器

System.out.println("迭代器:");
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()){
    String key = iterator.next();
    System.out.println(key + ":" + map.get(key));
}

Set<Map.Entry<String, Object>> entrySet = map.entrySet();
Iterator<Map.Entry<String, Object>> iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
    Map.Entry<String, Object> entryObj = iterator1.next();
    System.out.println(entryObj.getKey() + ":" + entryObj.getValue());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

测试

Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map.put("3", 3);
map.put("4", 4);
  • 1
  • 2
  • 3
  • 4
  • 5
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/564625
推荐阅读
相关标签
  

闽ICP备14008679号