HashMap遍历所有的key和value

简介: HashMap遍历所有的key和value

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());
}
相关文章
|
7月前
HashMap遍历方式
HashMap遍历方式
|
8月前
|
安全 Java API
java中HashMap的七种遍历方式
java.util.ConcurrentModificationException , 这种办法是非安全的 , 我们可以使用Iterator.remove() ,或者是Lambda 中的 removeIf() , 或者是Stream 中的 filter() 过滤或者删除相关数据
66 1
|
1月前
|
Java API
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
26 1
|
6月前
|
存储
HashMap HashTable ConcurrentMap 中key value是否可以为null
HashMap HashTable ConcurrentMap 中key value是否可以为null
49 0
|
11月前
|
存储 算法 安全
HashMap的遍历方式及底层原理
HashMap的遍历方式及底层原理
遍历HashMap的四种方式
遍历HashMap的四种方式
59 0
|
Java API
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!
171 0
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)
|
Java 编译器
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(1)
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!
118 0
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(1)
|
Java
Java:遍历HashMap的常用方法
Java:遍历HashMap的常用方法
122 0
HashMap,你是怎么做到的Key重复?
HashMap,你是怎么做到的Key重复?