Java 程序遍历 HashMap 的元素
javacampus interviewserver side programmingprogramming更新于 2024/8/8 20:36:00
在本文中,我们将了解如何遍历哈希映射的元素。Java HashMap 是基于哈希表的 Java Map 接口的实现。它是键值对的集合。
下面是相同的演示 −
假设我们的输入是 −
Run the program
期望的输出将是 −
HashMap 的元素包括: 1 : Java 2 : Python 3 : Scala 4 : Javascript
算法
步骤 1 - 开始 步骤 2 - 声明一个 HashMap,即 input_map。 步骤 3 - 定义值。 步骤 4 - 使用 for 循环进行迭代,使用 getKey() 和 getValue() 函数获取与索引关联的键和值。 步骤 5 - 显示结果 步骤 6 - 停止
示例 1
在这里,我们将所有操作都绑定在‘main’函数下。
import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String[] args){ System.out.println("Required packages have been imported"); Map<String, String> input_map = new HashMap<String, String>(); input_map.put("1", "Java"); input_map.put("2", "Python"); input_map.put("3", "Scala"); input_map.put("4", "Javascript"); System.out.println("A Hashmap is declared\n"); System.out.println("The elements of the HashMap are: "); for (Map.Entry<String, String> set : input_map.entrySet()) { System.out.println(set.getKey() + " : " + set.getValue()); } } }
输出
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
示例 2
在这里,我们将操作封装成展现面向对象编程的函数。
import java.util.HashMap; import java.util.Map; public class Demo { static void print(Map<String, String> input_map){ System.out.println("The elements of the HashMap are: "); for (Map.Entry<String, String> set : input_map.entrySet()) { System.out.println(set.getKey() + " : " + set.getValue()); } } public static void main(String[] args){ System.out.println("Required packages have been imported"); Map<String, String> input_map = new HashMap<String, String>(); input_map.put("1", "Java"); input_map.put("2", "Python"); input_map.put("3", "Scala"); input_map.put("4", "Javascript"); System.out.println("A Hashmap is declared\n"); print(input_map); } }
输出
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript