An interview question asked in a previous interview

HashMap in java is a data structure used to store pairs of "key" and "value" information. Unlike Array, ArrayList, and LinkedLists, it does not maintain the order in which elements are inserted.
So sorting HashMap based on key or value is a hard interview question if you don't know how to solve it. Let's see how to solve this problem.

1. HashMap stores each pair of key and value as an Entry<K,V> object. For example, given a HashMap,

Map<String,Integer> aMap = new HashMap<String,Integer>(); 

Each time the key is inserted, there will be a value corresponding to the hash map, and an Entry <K, V> object will be generated. By using this Entry<K,V> object, we can sort the HashMap based on the value.

2. Create a simple HashMap and insert some keys and values. 

Map<String, Object> map = new HashMap<>();
map.put("2", "李四");
map.put("1", "张三");
map.put("5", "六二");
map.put("4", "王五");

3. Restore the entry collection from the HashMap as shown below.

Set<Entry<String,Object>> mapEntries = map.entrySet();

4. Create LinkedList from above mapEntries. We will sort this linked list to solve the order problem. The reason we want to use a linked list for this purpose is because inserting elements in a linked list is faster than an array list.

List<Map.Entry<String, Object>> infoIds =
			    new LinkedList<Map.Entry<String, Object>>(mapEntries);

5. Use the Collections.sort() method to sort the linked list by passing the linked list and a custom comparator.

Collections.sort(infoIds,new Comparator<Map.Entry<String, Object>>() {
	@Override
	public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
		return Integer.valueOf(o2.getKey())-Integer.valueOf(o1.getKey());
	}
});

6. Use a custom comparator to sort the linked list based on the value of the entry (Entry.getKey()).

7. o2.getKey().compareTo(o1.getKey()) - compares the two values, returns 0 - if the two values ​​are exactly the same; returns 1 - if the first value is greater than the second value; returns -1 - if the first value is less than the second value.

8. Collections.sort() is a built-in method that only sorts a list of values. It is overloaded in Collections class. These two methods are

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 the key and value information pairs in the new map. Since HashMap does not maintain order, we want 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: infoIds) { 
        aMap2.put(entry.getKey(), entry.getValue()); 

10. The complete code is as follows.

import java.util.ArrayList;
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 HashMapTest {

	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		map.put("2", "李四");
		map.put("1", "张三");
		map.put("5", "六二");
		map.put("4", "王五");
		sortMapByValues(map);
		
	}

	private static void sortMapByValues(Map<String, Object> map) {
		System.out.println("排序前:");
		for (Entry<String, Object> entry : map.entrySet()) {
			System.out.println(entry.getKey()+"-"+entry.getValue());
		}
		
		Set<Entry<String,Object>> mapEntries = map.entrySet();
		
		List<Map.Entry<String, Object>> infoIds =
			    new LinkedList<Map.Entry<String, Object>>(mapEntries);
		
		Collections.sort(infoIds,new Comparator<Map.Entry<String, Object>>() {
			@Override
			public int compare(Entry<String, Object> o1, Entry<String, Object> o2) {
				return Integer.valueOf(o2.getKey())-Integer.valueOf(o1.getKey());
			}
		});
		
		
		Map<String, Object> map2 = new LinkedHashMap<>();
		
		for (Entry<String, Object> entry : infoIds) {
			map2.put(entry.getKey(), entry.getValue());
		}
		
		//打印排序后的Map
		System.out.println("打印排序后的Map:");
		for (Entry<String, Object> entry : map2.entrySet()) {
			System.out.println(entry.getKey()+"-"+entry.getValue());
		}
	}
	
	
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325451801&siteId=291194637