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());
}
相关文章
|
11月前
HashMap遍历方式
HashMap遍历方式
|
安全 Java API
java中HashMap的七种遍历方式
java.util.ConcurrentModificationException , 这种办法是非安全的 , 我们可以使用Iterator.remove() ,或者是Lambda 中的 removeIf() , 或者是Stream 中的 filter() 过滤或者删除相关数据
100 1
|
11天前
|
存储 开发者
HashMap和Hashtable的key和value可以为null吗,ConcurrentHashMap呢
HashMap的key可以为null,value也可以为null;Hashtable的key不允许为null,value也不能为null;ConcurrentHashMap的key不允许为null
|
3月前
|
存储 Java
Redis08命令-Hash类型,也叫散列,其中value是一个无序字典,类似于java的HashMap结构,Hash结构可以将对象中的每个字段独立存储,可以针对每字段做CRUD
Redis08命令-Hash类型,也叫散列,其中value是一个无序字典,类似于java的HashMap结构,Hash结构可以将对象中的每个字段独立存储,可以针对每字段做CRUD
|
5月前
|
Java API
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
40 1
Java-HashMap根据value排序
Java-HashMap根据value排序
|
10月前
|
存储
HashMap HashTable ConcurrentMap 中key value是否可以为null
HashMap HashTable ConcurrentMap 中key value是否可以为null
71 0
|
存储 算法 安全
HashMap的遍历方式及底层原理
HashMap的遍历方式及底层原理
遍历HashMap的四种方式
遍历HashMap的四种方式
80 0
|
Java API
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!
190 0
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)