In this article, we will understand how to sort map by keys. The Java Map interface, java.util.Map, represents a mapping between a key and a value. More specifically, a Java Map can store pairs of keys and values. Each key is linked to a specific value.
Below is a demonstration of the same −
Suppose our input is −
Input map: {1=Scala, 2=Python, 3=Java}
The desired output would be −
The sorted map with the key: {1=Scala, 2=Python, 3=Java}
Algorithm
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
Example 1
Here, we bind all the operations together under the ‘main’ function.
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); } }
Output
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}
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
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); } }
Output
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}