1、遍历entry,从entry中拿key和value
map.entrySet().forEach(entry -> { System.out.print(entry.getKey()+":"); System.out.println(entry.getValue()); });
2、单独遍历key和value
map.keySet().forEach(key->{ System.out.println(key); }); map.values().forEach(value->{ System.out.println(value); });
3、使用Iterator
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); System.out.print(entry.getKey()+":"); System.out.println(entry.getValue()); }
4、傻大粗,用key去找value
map.keySet().forEach(key->{ System.out.print(key+":"); System.out.println(map.get(key)); });
上面forEach都是用J8新特性,不喜欢用的话就用下面这个
for (Map.Entry entry : map.entrySet()) { System.out.print(entry.getKey() + ":"); System.out.println(entry.getValue()); }