Friday, May 10, 2019

How do you sort alphanumeric key of a map OR Sort map by key in java?

Problem statement:
How do you sort alphanumeric key of a map ?
Method-I:
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.TreeMap;
  5. public class SortAlphanumericKeyInMap {
  6.     public static void main(String[] args) {
  7.         Map<String, String> map = new HashMap<>();
  8.         map.put("question1", "1");
  9.         map.put("question9", "2");
  10.         map.put("question4", "2");
  11.         map.put("question6", "7");
  12.         // using TreeMap
  13.         Map<String, String> treeMap = new TreeMap<>(map);
  14.         Set<String> keys = treeMap.keySet();
  15.         for (String key : keys) {
  16.             System.out.println(key);
  17.         }
  18.     }
  19. }
Output:
question1
question4
question6
question9

Method-II:
import java.util.*;
public class SortAlphanumericKeyInMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("question1", "1");
        map.put("question9", "2");
        map.put("question4", "2");
        map.put("question6", "7");
        Set<String> set = map.keySet();
        // This will iterate across the map in natural order of the keys.
        SortedSet<String> keys = new TreeSet<>(set);
        for (String key : keys) {
            System.out.println("sorted key: " + key + " | values: " + map.get(key));
        }
    }
}
Output:
sorted key: question1 | values: 1
sorted key: question4 | values: 2
sorted key: question6 | values: 7
sorted key: question9 | values: 2

Method-III:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Collections;
public class SortAlphanumericKeyInMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("question1", "1");
        map.put("question9", "2");
        map.put("question4", "2");
        map.put("question6", "7");
        Set set = map.keySet();
        // using List
        List keys = new ArrayList(set);
        Collections.sort(keys);
        for (Object key : keys) {
            System.out.println(key);
        }
    }
}
Output:
question1
question4
question6
question9

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...