Java 程序,按键排序映射
在本文中,我们将了解如何按键对映射进行排序。Java Map 接口 java.util.Map 表示键和值之间的映射。更具体地说,Java Map 可以存储键值对。每个键都链接到一个特定的值。
以下是对相同的演示 −
假设我们的输入是 −
Input map: {1=Scala, 2=Python, 3=Java}
理想的输出如下 −
The sorted map with the key: {1=Scala, 2=Python, 3=Java}
算法
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create a Map structure, and add values to it using the ‘put’ method. Step 5 - Create a TreeMap of strings. Step 6 - The Map sorts the values based on keys and stores it in TreeMap. Step 7 - Display this on the console. Step 8 - Stop
示例 1
在这里,我们把所有操作都绑定在“main”函数下。
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Demo { public static void main(String[] args) { System.out.println("The required packages have been imported"); Map<String, String> input_map = new HashMap<>(); input_map.put("1", "Scala"); input_map.put("3", "Java"); input_map.put("2", "Python"); System.out.println("The map is defined as: " + input_map); TreeMap<String, String> result_map = new TreeMap<>(input_map); System.out.println("\nThe sorted map with the key: \n" + result_map); } }
输出
The required packages have been imported The map is defined as: {1=Scala, 2=Python, 3=Java} The sorted map with the key: {1=Scala, 2=Python, 3=Java}
示例 2
在这里,我们将把操作封装到函数中,展示面向对象编程。
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Demo { static void sort( Map<String, String> input_map){ TreeMap<String, String> result_map = new TreeMap<>(input_map); System.out.println("\nThe sorted map with the key: \n" + result_map); } public static void main(String[] args) { System.out.println("The required packages have been imported"); Map<String, String> input_map = new HashMap<>(); input_map.put("1", "Scala"); input_map.put("3", "Java"); input_map.put("2", "Python"); System.out.println("The map is defined as: " + input_map); sort(input_map); } }
输出
The required packages have been imported The map is defined as: {1=Scala, 2=Python, 3=Java} The sorted map with the key: {1=Scala, 2=Python, 3=Java}
广告