java 散列遍历

Map map = new HashMap<>();
map.put("name","dj");

1.foreach遍历

for e : map.entrySet()>;
sout(e.getKey() + e.getValue());

2.foreach遍历键或值

for(String k : map.keySet())
sout(k);

3.使用带泛型的迭代器

Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()){
Map.Entry entry = entries.next();
sout(entry.getKey());
}

4.lambda遍历

map.forEach((k,v) -> sout(k+v));

 

 

5.不带泛型的迭代器

        // 4.使用不带泛型的迭代器  (报错)
//        Iterator 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);

 

你可能感兴趣的:(Java)