Java interview questions: how to sort HashMap key values

Source: Internet
Author: User

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,

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

 
 
  1. ap<String,Integer> aMap = new HashMap<String,Integer>(); 
  2.  
  3.         // adding keys and values 
  4.         aMap.put("Five", 5); 
  5.         aMap.put("Seven", 7); 
  6.         aMap.put("Eight", 8); 
  7.         aMap.put("One",1); 
  8.         aMap.put("Two",2); 
  9.         aMap.put("Three", 3); 

3. Restore the entry set from HashMap, as shown below.

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

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

 
 
  1. Collections.sort(aList, new Comparator<Entry<String,Integer>>() { 
  2.  
  3.             @Override 
  4.  
  5.             public int compare(Entry<String, Integer> ele1, 
  6.  
  7.                     Entry<String, Integer> ele2) { 
  8.  
  9.                 return ele1.getValue().compareTo(ele2.getValue()); 
  10.  
  11.             } 
  12.  
  13.         }); 

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:

 
 
  1. public static <T extends Comparable<? super T>> void sort(List<T> list) 
  2.  
  3. 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.

 
 
  1. // Storing the list into Linked HashMap to preserve the order of insertion.      
  2. Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>(); 
  3.         for(Entry<String,Integer> entry: aList) { 
  4.             aMap2.put(entry.getKey(), entry.getValue()); 
  5.         } 

10. The complete code is as follows.

 
 
  1. package com.speakingcs.maps; 
  2.  
  3. import java.util.Collections; 
  4. import java.util.Comparator; 
  5. import java.util.HashMap; 
  6. import java.util.LinkedHashMap; 
  7. import java.util.LinkedList; 
  8. import java.util.List; 
  9. import java.util.Map; 
  10. import java.util.Map.Entry; 
  11. import java.util.Set; 
  12.  
  13. public class SortMapByValues { 
  14.  
  15.     public static void main(String[] args) { 
  16.  
  17.         Map<String,Integer> aMap = new HashMap<String,Integer>(); 
  18.  
  19.         // adding keys and values 
  20.         aMap.put("Five", 5); 
  21.         aMap.put("Seven", 7); 
  22.         aMap.put("Eight", 8); 
  23.         aMap.put("One",1); 
  24.         aMap.put("Two",2); 
  25.         aMap.put("Three", 3); 
  26.  
  27.         sortMapByValues(aMap); 
  28.  
  29.     } 
  30.  
  31.     private static void sortMapByValues(Map<String, Integer> aMap) { 
  32.  
  33.         Set<Entry<String,Integer>> mapEntries = aMap.entrySet(); 
  34.  
  35.         System.out.println("Values and Keys before sorting "); 
  36.         for(Entry<String,Integer> entry : mapEntries) { 
  37.             System.out.println(entry.getValue() + " - "+ entry.getKey()); 
  38.         } 
  39.  
  40.         // used linked list to sort, because insertion of elements in linked list is faster than an array list. 
  41.         List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries); 
  42.  
  43.         // sorting the List 
  44.         Collections.sort(aList, new Comparator<Entry<String,Integer>>() { 
  45.  
  46.             @Override 
  47.             public int compare(Entry<String, Integer> ele1, 
  48.                     Entry<String, Integer> ele2) { 
  49.  
  50.                 return ele1.getValue().compareTo(ele2.getValue()); 
  51.             } 
  52.         }); 
  53.  
  54.         // Storing the list into Linked HashMap to preserve the order of insertion. 
  55.         Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>(); 
  56.         for(Entry<String,Integer> entry: aList) { 
  57.             aMap2.put(entry.getKey(), entry.getValue()); 
  58.         } 
  59.  
  60.         // printing values after soring of map 
  61.         System.out.println("Value " + " - " + "Key"); 
  62.         for(Entry<String,Integer> entry : aMap2.entrySet()) { 
  63.             System.out.println(entry.getValue() + " - " + entry.getKey()); 
  64.         } 
  65.  
  66.     } 

Http://www.codeceo.com/article/java-hashmap-value-sort.html.
How to Sort HashMap Based On Values in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.