赞
踩
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");
Iterator<Map.Entry<Integer, String>> iterator = coursesMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry <Integer, String> entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
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");
// 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));
}
}
}
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");
// 3. 使用 For-each 循环遍历 HashMap
for (Map.Entry<Integer, String> entry: coursesMap.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
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");
// 4. 使用 Lambda 表达式遍历 HashMap
coursesMap.forEach((key, value) -> {
System.out.println(key);
System.out.println(value);
});
}
}
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");
// 5. 使用 Stream API 遍历 HashMap
coursesMap.entrySet().stream().forEach((entry) - > {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。