HashMap遍历方式

简介: HashMap遍历方式
// 通过Map.values()遍历所有的value,但不能遍历key
for(String v:map.values()){
 System.out.println("The value is "+v);
}
// 迭代器 EntrySet 方式遍历 -- 性能稍好 一次取值
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
    Map.Entry<Integer, String> next = iterator.next();
    System.out.println(next.getKey());
    System.out.println(next.getValue());
}
// 迭代器的 KeySet 方式遍历  
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()){
    Integer key = iterator.next();
    System.out.print(key);
    System.out.print(map.get(key));
}
//  For Each EntrySet 方式遍历 -- 推荐,尤其是容量大时 
for (Map.Entry<Integer,String> entry: map.entrySet()) {
    System.out.println("entry.getKey() = " + entry.getKey());
    System.out.println("entry.getValue() = " + entry.getValue());
}
// For Each KeySet 方式遍历  -- 普通使用,二次取值(性能差)
for (Integer key: map.keySet()) {
    System.out.println(key);
    System.out.println(map.get(key));
}
// Lambda 表达式方式遍历
map.forEach((key,value) -> {
    System.out.print(key);
    System.out.print(value);
});
// Streams API 单线程方式遍历
map.entrySet().stream().forEach((integerStringEntry -> {
    System.out.println(integerStringEntry.getKey());
    System.out.println(integerStringEntry.getValue());
}));
// Streams API 多线程方式遍历
map.entrySet().parallelStream().forEach((integerStringEntry -> {
    System.out.println(integerStringEntry.getKey());
    System.out.println(integerStringEntry.getValue());
}));


相关文章
|
安全 Java API
java中HashMap的七种遍历方式
java.util.ConcurrentModificationException , 这种办法是非安全的 , 我们可以使用Iterator.remove() ,或者是Lambda 中的 removeIf() , 或者是Stream 中的 filter() 过滤或者删除相关数据
198 1
|
Java API
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
面试官上来就让手撕HashMap的7种遍历方式,当场愣住,最后只写出了3种
88 1
|
Java 数据库连接 API
HashMap 的 7 种遍历方式与性能分析!(强烈推荐)上
HashMap 的 7 种遍历方式与性能分析!(强烈推荐)
362 0
HashMap 的 7 种遍历方式与性能分析!(强烈推荐)上
|
Java API
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!
242 0
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(2)
|
Java 编译器
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(1)
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!
201 0
公司新来一个同事:为什么 HashMap 不能一边遍历一边删除?一下子把我问懵了!(1)
|
存储 算法 安全
HashMap的遍历方式及底层原理
HashMap的遍历方式及底层原理
遍历HashMap的四种方式
遍历HashMap的四种方式
187 0
|
JavaScript 小程序 Java
HashMap 为什么不能一边遍历一遍删除
HashMap 为什么不能一边遍历一遍删除
|
Java
Java:遍历HashMap的常用方法
Java:遍历HashMap的常用方法
171 0
|
Java
【Java系列】HashMap的6种遍历方法
通过对map entrySet的遍历,也可以同时拿到key和value,一般情况下,性能上要优于上一种,这一种也是最常用的遍历方法。
288 0
【Java系列】HashMap的6种遍历方法