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 ?

  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("A1BB", "1");
  9.         map.put("A2CC", "2");
  10.         map.put("A2AA", "2");
  11.         map.put("B1AA", "7");
  12.         Map<String, String> treeMap = new TreeMap<>(map);
  13.         Set<String> keys = treeMap.keySet();
  14.         for (String key : keys) {
  15.             System.out.println(key);
  16.         }
  17.     }
  18. }
Output:
A1BB
A2AA

A2CC
B1AA

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...