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}

更新於: 30-3-2022

469 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.