- 使用 Iterator 遍历 HashMap EntrySet
- 使用 Iterator 遍历 HashMap KeySet
- 使用 For-each 循环迭代 HashMap
- 使用 Lambda 表达式遍历 HashMap
- 使用 Stream API 遍历 HashMap
1. 使用 Iterator 遍历 HashMap EntrySet
public class IterateHashMapExample {
public static void main(String[] args) {
// 1. 使用 Iterator 遍历 HashMap EntrySet
Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "Spring Framework");
coursesMap.put(5, "Hibernate ORM framework");
Iterator < Entry < Integer, String >> iterator = coursesMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry < Integer, String > entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
2. 使用 Iterator 遍历 HashMap KeySet
public class IterateHashMapExample {
public static void main(String[] args) {
Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "Spring Framework");
coursesMap.put(5, "Hibernate ORM framework");
// 2. 使用 Iterator 遍历 HashMap KeySet
Iterator < Integer > iterator = coursesMap.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
System.out.println(key);
System.out.println(coursesMap.get(key));
}
}
}
3. 使用 For-each 循环遍历 HashMap
public class IterateHashMapExample {
public static void main(String[] args) {
Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "Spring Framework");
coursesMap.put(5, "Hibernate ORM framework");
// 3. 使用 For-each 循环遍历 HashMap
for (Map.Entry < Integer, String > entry: coursesMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
4. 使用 Lambda 表达式遍历 HashMap
public class IterateHashMapExample {
public static void main(String[] args) {
Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "Spring Framework");
coursesMap.put(5, "Hibernate ORM framework");
// 4. 使用 Lambda 表达式遍历 HashMap
coursesMap.forEach((key, value) -> {
System.out.println(key);
System.out.println(value);
});
}
}
5. 使用 Stream API 遍历 HashMap
public class IterateHashMapExample {
public static void main(String[] args) {
Map < Integer, String > coursesMap = new HashMap < Integer, String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "Spring Framework");
coursesMap.put(5, "Hibernate ORM framework");
// 5. 使用 Stream API 遍历 HashMap
coursesMap.entrySet().stream().forEach((entry) - > {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
}
}