이 기사에서는 키로 맵을 정렬하는 방법을 이해합니다. 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
여기에서 모든 작업을 '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}