面试官这样问,虽然答出来了,但是很不爽,这不就是和孔乙己的茴香豆有几种写法嘛!
Map<String, String> hashMap = new HashMap<>(2);
hashMap.put("a", "pretty");
hashMap.put("b", "great");
// 1 使用增强for的方式来遍历hashMap
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
// 2 使用Lambda表达式的方式来遍历hashMap,k,v
hashMap.forEach((k, v) -> {
System.out.println(k + ": " + v);
});
// 3 key遍历
for (String key : hashMap.keySet()) {
System.out.println(key + ": " + hashMap.getOrDefault(key, ""));
}
// 4 迭代器遍历
Iterator<Map.Entry<String, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println(next.getKey() + ": " + next.getValue());
}
// 5 lambda单线程
hashMap.entrySet().stream().forEach((entry) -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
// 6 多线程,单核性能会有上下文切换!
int availableProcessors = Runtime.getRuntime().availableProcessors();
if (availableProcessors > 2) {
hashMap.entrySet().parallelStream().forEach(entry -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}