java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java HashMap遍历

java中HashMap的七种遍历方式小结

作者:IT枫斗者

本文主要介绍了java中HashMap的七种遍历方式小结,包括迭代器,For Each,Lambda,Streams API等,具有一定的参考价值,感兴趣的可以了解一下

HashMap遍历方式分类

迭代器(Iterator)EntrySet

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

Iterator<Map.Entry<String, String>> iterator = hashMap.entrySet().iterator();

while (iterator.hasNext()) {
    Map.Entry<String, String> entry = iterator.next();
    Object key = entry.getKey();
    Object val = entry.getValue();
    System.out.println("key : " + key + "-----" + "val : " + val);
}

迭代器(Iterator)KeySet

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

Iterator<String> iterator = hashMap.keySet().iterator();

while (iterator.hasNext()) {
    String key = iterator.next();
    Object val = hashMap.get(key);
    System.out.println("key : " + key + "-----" + "val : " + val);
}

For Each EntrySet

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

for (Map.Entry<String, String> entry : hashMap.entrySet()) {
    Object key = entry.getKey();
    Object val = entry.getValue();
    System.out.println("key : " + key + "-----" + "val : " + val);
}

For Each KeySet

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

for (String key : hashMap.keySet()) {
    Object val = hashMap.get(key);
    System.out.println("key : " + key + "-----" + "val : " + val);
}

Lambda

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

hashMap.forEach((key , val) -> System.out.println("key : " + key + "-----" + "val : " + val));

Streams API 单线程

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

hashMap.entrySet().stream().forEach((entry) -> {
    Object key = entry.getKey();
    Object val = entry.getValue();
    System.out.println("key : " + key + "-----" + "val : " + val);
});

Streams API 多线程

HashMap<String , String> hashMap = new HashMap<>();

hashMap.put("1","name");
hashMap.put("2","age");

hashMap.entrySet().stream().parallel().forEach((entry) -> {
    Object key = entry.getKey();
    Object val = entry.getValue();
    System.out.println("key : " + key + "-----" + "val : " + val);
});

到此这篇关于java中HashMap的七种遍历方式小结的文章就介绍到这了,更多相关java HashMap遍历内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文