Java Program to Sort map by keys

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.

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

Example 2 :Java Program to sort map by keys using Treemaps 

Run

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

Example 3: 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<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

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription