按键对地图进行排序的 Java 程序

javacampus interviewserver side programmingprogramming

在本文中,我们将了解如何按键对地图进行排序。Java Map 接口 java.util.Map 表示键和值之间的映射。更具体地说,Java Map 可以存储键和值对。每个键都链接到一个特定值。

下面是相同的演示 −

假设我们的输入是

输入映射:{1=Scala, 2=Python, 3=Java}

期望输出的将是

带有键的排序映射:
{1=Scala, 2=Python, 3=Java}

算法

步骤 1 - 开始
步骤 2 - 声明
步骤 3 - 定义值。
步骤 4 - 创建 Map 结构,并使用 ‘put’ 方法向其添加值。
步骤 5 - 创建字符串的 TreeMap。
步骤 6 - Map 根据键对值进行排序并将其存储在 TreeMap 中。
步骤 7 - 在控制台上显示此信息。
步骤 8 - 停止

示例 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}

相关文章