Java interview questions: how to sort HashMap key values
In Java, HashMap is a data structure used to store "key" and "value" Information pairs. Unlike Array, ArrayList, and lists, it does not maintain the order of inserted elements.
Therefore, sorting HashMap Based on keys or values is a very difficult interview question if you do not know how to solve it. Next let's take a look at how to solve this problem.
1. HashMap stores each key and value pair as an Entry <K, V> object. For example, a HashMap,
- Map<String,Integer> aMap = new HashMap<String,Integer>();
Each time a key is inserted, a value is mapped to the hash ing to generate an Entry <K, V> object. By using this Entry <K, V> object, we can sort HashMap by value.
2. Create a simple HashMap and insert some keys and values.
- ap<String,Integer> aMap = new HashMap<String,Integer>();
-
- // adding keys and values
- aMap.put("Five", 5);
- aMap.put("Seven", 7);
- aMap.put("Eight", 8);
- aMap.put("One",1);
- aMap.put("Two",2);
- aMap.put("Three", 3);
3. Restore the entry set from HashMap, as shown below.
- Set<Entry<String,Integer>> mapEntries = aMap.entrySet();
4. Create an external list from mapEntries. We will sort the linked list to solve the sequence problem. We want to use the linked list to achieve this goal, because inserting elements in the linked list is faster than the list of arrays.
- List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);
5. Use the Collections. sort () method to sort the linked list by passing the linked list and the custom comparator.
- Collections.sort(aList, new Comparator<Entry<String,Integer>>() {
-
- @Override
-
- public int compare(Entry<String, Integer> ele1,
-
- Entry<String, Integer> ele2) {
-
- return ele1.getValue().compareTo(ele2.getValue());
-
- }
-
- });
6. Use a custom comparator to sort the linked list based on the entry value Entry. getValue.
7. ele1.getValue (). compareTo (ele2.getValue () -- compare the two values and return 0 -- if the two values are identical; return 1 -- if the first value is greater than the second value; return-1 -- if the first value is smaller than the second value.
8. Collections. sort () is a built-in method that only sorts the list of values. It is reloaded in the Collections class. The two methods are as follows:
- public static <T extends Comparable<? super T>> void sort(List<T> list)
-
- public static <T> void sort(List<T> list, Comparator<? super T> c)
9. Now that you have sorted the linked list, we need to store key-value pairs to the new ing. Because HashMap does not maintain the order, we need to use LinkedHashMap.
- // Storing the list into Linked HashMap to preserve the order of insertion.
- Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();
- for(Entry<String,Integer> entry: aList) {
- aMap2.put(entry.getKey(), entry.getValue());
- }
10. The complete code is as follows.
- package com.speakingcs.maps;
-
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.LinkedHashMap;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
-
- public class SortMapByValues {
-
- public static void main(String[] args) {
-
- Map<String,Integer> aMap = new HashMap<String,Integer>();
-
- // adding keys and values
- aMap.put("Five", 5);
- aMap.put("Seven", 7);
- aMap.put("Eight", 8);
- aMap.put("One",1);
- aMap.put("Two",2);
- aMap.put("Three", 3);
-
- sortMapByValues(aMap);
-
- }
-
- private static void sortMapByValues(Map<String, Integer> aMap) {
-
- Set<Entry<String,Integer>> mapEntries = aMap.entrySet();
-
- System.out.println("Values and Keys before sorting ");
- for(Entry<String,Integer> entry : mapEntries) {
- System.out.println(entry.getValue() + " - "+ entry.getKey());
- }
-
- // used linked list to sort, because insertion of elements in linked list is faster than an array list.
- List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);
-
- // sorting the List
- Collections.sort(aList, new Comparator<Entry<String,Integer>>() {
-
- @Override
- public int compare(Entry<String, Integer> ele1,
- Entry<String, Integer> ele2) {
-
- return ele1.getValue().compareTo(ele2.getValue());
- }
- });
-
- // Storing the list into Linked HashMap to preserve the order of insertion.
- Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();
- for(Entry<String,Integer> entry: aList) {
- aMap2.put(entry.getKey(), entry.getValue());
- }
-
- // printing values after soring of map
- System.out.println("Value " + " - " + "Key");
- for(Entry<String,Integer> entry : aMap2.entrySet()) {
- System.out.println(entry.getValue() + " - " + entry.getKey());
- }
-
- }
- }
Http://www.codeceo.com/article/java-hashmap-value-sort.html.
How to Sort HashMap Based On Values in Java