Problem statement:
How do you sort alphanumeric key of a map ?
Method-I:
Method-III:
How do you sort alphanumeric key of a map ?
Method-I:
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- 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");
- // using TreeMap
- Map<String, String> treeMap = new TreeMap<>(map);
- Set<String> keys = treeMap.keySet();
- for (String key : keys) {
- System.out.println(key);
- }
- }
- }
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.
// 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
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