Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อจัดเรียงแผนที่ตามคีย์


ในบทความนี้ เราจะเข้าใจวิธีการจัดเรียงแผนที่ด้วยปุ่มต่างๆ อินเทอร์เฟซ Java Map java.util.Map แสดงถึงการแมประหว่างคีย์และค่า โดยเฉพาะอย่างยิ่ง Java Mapcan เก็บคู่ของคีย์และค่าต่างๆ แต่ละคีย์เชื่อมโยงกับค่าเฉพาะ

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

สมมติว่าข้อมูลที่เราป้อนคือ

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

ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'

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}