Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để sắp xếp bản đồ theo các phím

Trong bài này, chúng ta sẽ hiểu cách sắp xếp bản đồ theo các phím. Giao diện Java Map, java.util.Map, đại diện cho một ánh xạ giữa một khóa và một giá trị. Cụ thể hơn, Java Mapcan lưu trữ các cặp khóa và giá trị. Mỗi khóa được liên kết với một giá trị cụ thể.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

Input map: {1=Scala, 2=Python, 3=Java}

Đầu ra mong muốn sẽ là -

The sorted map with the key:
{1=Scala, 2=Python, 3=Java}

Thuật toán

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

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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);
   }
}

Đầu ra

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}

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm trưng bày lập trình hướng đối tượng.

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);
   }
}

Đầu ra

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}