HashMap遍历
HashMap的遍历总共可以分为以下四类
- Iterator遍历
- For Each遍历
- Lambda表达式遍历
- Stream API遍历
Iterator迭代器遍历
Iterator结合entrySet遍历
// Iterator 结合entry遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
Iterator<Map.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Iterator结合keySet遍历
// Iterator 结合keyset遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
Iterator<Integer> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
int key = iterator.next();
System.out.println(hashMap.get(key));
}
For Each遍历
For Each结合entrySet遍历
// for 结合entrySet遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
For Each结合keySet遍历
// for 结合keySet遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
for (Integer key : hashMap.keySet()) {
System.out.println(key);
System.out.println(hashMap.get(key));
}
Lambda表达式遍历
// Lambda表达式遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
hashMap.forEach((key, value) -> {
System.out.println(key);
System.out.println(value);
});
Stream API遍历
Stream API单线程遍历
// Streanms API单线程遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
hashMap.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
Stream API多线程遍历
// Streanms API多线程遍历HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "a");
hashMap.put(2, "b");
hashMap.put(3, "c");
System.out.println(hashMap);
hashMap.entrySet().parallelStream().forEach((entry) -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
参考:
标签:遍历,HashMap,七大,System,println,put,out,hashMap From: https://www.cnblogs.com/sheayu/p/17956107