Java 程序迭代 HashMap
javacampus interviewserver side programmingprogramming
在本文中,我们将了解如何迭代 HashMap。Java HashMap 是基于哈希表的 Java Map 接口实现。它是键值对的集合。
下面是相同的演示 −
假设我们的输入是 −
Input Hashmap: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI}
期望的输出将是 −
The keys of the Hashmap are: Java, JavaScript, Mysql, Python, The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,
算法
步骤 1 - 开始 步骤 2 - 声明即 步骤 3 - 定义值。 步骤 4 - 创建字符串哈希图并使用 ‘put’ 方法初始化其中的元素。 步骤 5 - 在控制台上显示哈希图。 步骤 6 - 遍历哈希图的元素,并使用 ‘keySet’ 方法获取每个键。 步骤 7 - 在控制台上显示。 步骤 6 - 停止
示例 1
在这里,我们将所有操作都绑定在‘main’函数下。
import java.util.HashMap; import java.util.Map.Entry; public class Demo { public static void main(String[] args) { System.out.println("The required packages have been imported"); HashMap<String, String> input_map = new HashMap<>(); input_map.put("Java", "Enterprise"); input_map.put("Python", "ML/AI"); input_map.put("JavaScript", "Frontend"); input_map.put("Mysql", "Backend"); System.out.println("The HashMap is defined as: " + input_map); System.out.print("\nThe keys of the Hashmap are: "); for(String key: input_map.keySet()) { System.out.print(key); System.out.print(", "); } System.out.print("\nThe Values of the Hashmap are: "); for(String value: input_map.values()) { System.out.print(value); System.out.print(", "); } } }
输出
The required packages have been imported The HashMap is defined as: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI} The keys of the Hashmap are: Java, JavaScript, Mysql, Python, The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,
示例 2
在这里,我们将操作封装成展现面向对象编程的函数。
import java.util.HashMap; public class Demo { static void print_keys(HashMap<String, String> input_map){ System.out.print("\nThe keys of the Hashmap are: "); for(String key: input_map.keySet()) { System.out.print(key); System.out.print(", "); } } static void print_values( HashMap<String, String> input_map){ System.out.print("\nThe Values of the Hashmap are: "); for(String value: input_map.values()) { System.out.print(value); System.out.print(", "); } } public static void main(String[] args) { System.out.println("The required packages have been imported"); HashMap<String, String> input_map = new HashMap<>(); input_map.put("Java", "Enterprise"); input_map.put("Python", "ML/AI"); input_map.put("JavaScript", "Frontend"); input_map.put("Mysql", "Backend"); System.out.println("The HashMap is defined as: " + input_map); print_keys(input_map); print_values(input_map); } }
输出
The required packages have been imported The HashMap is defined as: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI} The keys of the Hashmap are: Java, JavaScript, Mysql, Python, The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,