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}