Java Program to Sort map by keys
Java Map Interface
The java.util.Map interface in Java is a part of the Java Collections Framework and provides a collection view of key-value pairs. It is the base interface for several concrete implementation classes such as HashMap, TreeMap, LinkedHashMap, etc.
- An associative container known as a map maps distinct keys to values. Although duplicate values are permitted, duplicate keys are not. Using the put, get, and remove methods, you can add, get, and remove elements from a Map, respectively.
To know more about Java Program to Sort map by keys read the complete article.
Steps for Program to sort map by keys:
- Create a map and insert key-value pairs into it.
- Convert the map into a set of Map.Entry objects.
Create a list of the set and sort it using the Collections.sort method and a custom comparator that compares the keys. - Create a LinkedHashMap and insert the sorted entries.
- Return the LinkedHashMap.
Java Hash Map:
- HashMap is a class in Java's standard library that implements a hash table, which is a data structure that maps keys to values.A hash table is a data structure that maps keys to values, and the HashMap class in Java's standard library does just that. In order to support big datasets and quick lookups, hash maps offer constant-time average complexity for fundamental operations like get and put.
Java Tree Map:
- TreeMap is a class in Java's standard library that implements a Red-Black tree, a type of self-balancing binary search tree. It is a map that associates keys with values, however in contrast to HashMap, keys in a TreeMap are arranged either naturally or according to a unique Comparator.
Let’s look at a Java Program to Sort map by keys.
Example 1: Java Program to sort map by keys using Treemaps
Run
import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] args) { // Create a map Map<Integer, String> map = new TreeMap<>(); map.put(1, "Value1"); map.put(3, "Value3"); map.put(2, "Value2"); // Sort the map by keys using TreeMap Map<Integer, String> sortedMap = new TreeMap<>(map); // Print the sorted map for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } } }
Output
Key: 1, Value: Value1 Key: 2, Value: Value2 Key: 3, Value: Value3
Explanation:
- The code sorts a map by keys using TreeMap in Java. It creates a TreeMap map and adds key-value pairs to it. Then, it creates a new TreeMap sortedMap initialized with map, which sorts the keys of map in ascending order. Finally, the code prints the sorted map using a for loop and entrySet() method.
Example 2 :Java Program to sort map by keys using Treemaps
import java.util.Map; import java.util.TreeMap; class Person implements Comparable { private int id; private String name; public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Person o) { return Integer.compare(this.id, o.id); } } public class Main { public static void main(String[] args) { // Create a map Map<Person, String> map = new TreeMap<>(); map.put(new Person(3, "Person3"), "value3"); map.put(new Person(1, "Person1"), "Value1"); map.put(new Person(2, "Person2"), "Value2"); // Print the sorted map for (Map.Entry<Person, String> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey().getId() + ", Value: " + entry.getValue()); } } }
Output
Key: 1, Value: Value1 Key: 2, Value: Value2 Key: 3, Value: value3
Explanation:
This code demonstrates how to sort a map by its keys using a TreeMap in Java.
The Person class implements the Comparable interface and overrides the compareTo method, which specifies the sorting order for the keys of the map. In this example, the keys are sorted based on the id attribute of the Person object.
The Main class creates a TreeMap map and adds key-value pairs to it using the put method.
The for loop iterates over the entries of the map and prints the key and value of each entry.
The code will output the sorted map based on the id attribute of the Person object.
Example 3: Java Program to sort map by keys using Treemaps
import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] args) { // Create a map Map<String, Integer> map = new TreeMap<>(); map.put("apple", 1); map.put("banana", 3); map.put("cherry", 2); // Print the sorted map for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } } }
Output
Key: apple, Value: 1 Key: banana, Value: 3 Key: cherry, Value: 2
Explanation:
- This code demonstrates how to sort a map by its keys using a TreeMap in Java.
- The Main class creates a TreeMap map and adds key-value pairs to it using the put method.
- The for loop iterates over the entries of the map and prints the key and value of each entry using the entry.getKey() and entry.getValue() methods, respectively.
- When run, the code will output the sorted map based on the keys in ascending order
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment