java 散列遍历
程序员文章站
2022-03-15 20:46:03
...
Map<String,String> map = new HashMap<>();
map.put("name","dj");
1.foreach遍历
for<Map.Entry<String,String> e : map.entrySet()>;
sout(e.getKey() + e.getValue());
2.foreach遍历键或值
for(String k : map.keySet())
sout(k);
3.使用带泛型的迭代器
Iterator<Map.Entry<String,String>> entries = map.entrySet().iterator();
while (entries.hasNext()){
Map.Entry<String,String> entry = entries.next();
sout(entry.getKey());
}
4.lambda遍历
map.forEach((k,v) -> sout(k+v));
5.不带泛型的迭代器
// 4.使用不带泛型的迭代器 (报错)
// Iterator<Map.Entry> entries = map.entrySet().iterator();
// while (entries.hasNext()) {
// Map.Entry entry = (Map.Entry) entries.next();
// Integer key = (Integer) entry.getKey();
// Integer value = (Integer) entry.getValue();
// System.out.println("Key = " + key + ", Value = " + value);