HashMap遍历 (四种方法+7种实现方式)
HashMap遍历从大的方向来说,可分为一下4类:
1、迭代器(Iterator)方式;
2、foreach方式;
3、lambda表达式(JDK 1.8+);
4、Streams API(JDK 1.8+);
每种类型下又有不同的实现方式,因此具体的遍历方式又可以分为一下7种:
1、使用迭代器(Iterator)EntrySet的方式;
2、使用迭代器(Iterator)KeySet的方式;
3、使用foreach EntrySet的方式;
4、使用foreach KeySet的方式;
5、使用lambda表达式的方式;
6、使用StreamsAPI单线程的方式;
7、使用StreamsAPI多线程的方式;
接下来来看每种遍历方式的具体实现代码:
一、迭代器EntrySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.print(entry.getKey());
System.out.print(entry.getValue());
}
}
}
二、迭代器KeySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
System.out.print(key);
System.out.print(map.get(key));
}
}
}
三、foreach EntrySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.print(entry.getKey());
System.out.print(entry.getValue());
}
}
}
四、foreach KeySet
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
for (Integer key : map.keySet()) {
System.out.print(key);
System.out.print(map.get(key));
}
}
}
五、lambda
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
map.forEach((key, value) -> {
System.out.print(key);
System.out.print(value);
});
}
}
六、StreamsAPI单线程
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
map.entrySet().stream().forEach((entry) -> {
System.out.print(entry.getKey());
System.out.print(entry.getValue());
});
}
}
七、StreamsAPI多线程
public class HashMapTest {
public static void main(String[] args) {
// 创建并赋值 HashMap
Map<Integer, String> map = new HashMap();
map.put(1, "Java");
map.put(2, "JDK");
map.put(3, "Spring");
map.put(4, "MyBatis");
// 遍历
map.entrySet().parallelStream().forEach((entry) -> {
System.out.print(entry.getKey());
System.out.print(entry.getValue());
});
}
}