Java面试题:如何对HashMap按键值排序

Java中HashMap是一种用于存储“键”和“值”信息对的数据结构。不同于LinkedHashMap,它不会维持插入元素的顺序。因此,在键或值的基础上排序HashMap是一个很难的面试问题,如果你不知道如何解决的话。下面让我们看看如何解决这个问题。

1.创建一个简单的HashMap,并插入一些键和值。

Map aMap = new HashMap(); 
//adding keys and values 
aMap.put("Five", 5); 
aMap.put("Seven", 7);
aMap.put("Four", 4);
aMap.put("Eight", 8); 
aMap.put("One", 1); 
aMap.put("Two", 2); 
aMap.put("Three", 3); 
2.利用Set entrySet(): 返回Map.Entry对象的视图集,即映像中的关键字/值对

 Set> mapEntries = aMap.entrySet();
3.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题

List> aList = new LinkedList>(mapEntries); 
// sorting the List 
Collections.sort(aList, new Comparator>(){
	@Override 
	public int compare(Map.Entry ele1, Map.Entry ele2){
	    return ele1.getValue().compareTo(ele2.getValue()); 
	}
}); 
4.Collections.sort()是一个内置方法,仅排序值的列表。它在Collections类中重载。这两种个方法是

public static > void sort(List list) 

public static  void sort(List list, Comparator c) 
5.完整代码:

package cn.edu.ahui;
import java.util.*; 

/*
 * @author leo
 * @data 2017.3.10
*/

public class SortHashMapByValues {
	 private static void sortMapByValues(Map aMap){
		 Set> mapEntries = aMap.entrySet();
	     System.out.println("Values and Keys before sorting "); 
	     for(Map.Entry entry : mapEntries)
	    	 System.out.println(entry.getKey() + " - "+ entry.getValue()); 
	     //use LinkedList to sort, because insertion of elements in linked list is faster than ArrayList. 
	     List> aList = new LinkedList>(mapEntries); 
	     // sorting the List 
	     Collections.sort(aList, new Comparator>(){
	    	 @Override 
	         public int compare(Map.Entry ele1, Map.Entry ele2){
	    		 return ele1.getValue().compareTo(ele2.getValue()); 
	        }
	     }); 
	     // Storing the list into Linked HashMap to preserve the order of insertion. 
	     Map aMap2 = new LinkedHashMap();
	     for(Map.Entry entry: aList){
	    	 aMap2.put(entry.getKey(), entry.getValue()); 
	     } 
	     // printing values after sorting of map 
	     System.out.println("Values and Keys after sorting "); 
	     for(Map.Entry entry : aMap2.entrySet()){
	    	 System.out.println(entry.getKey() + " - " + entry.getValue()); 
	     } 
	} 
	public static void main(String[] args){
		Map aMap = new HashMap(); 
        //adding keys and values 
        aMap.put("Five", 5); 
        aMap.put("Seven", 7);
        aMap.put("Four", 4);
        aMap.put("Eight", 8); 
        aMap.put("One", 1); 
        aMap.put("Two", 2); 
        aMap.put("Three", 3); 
        sortMapByValues(aMap); 
    }  
}
6.运行结果:

Values and Keys before sorting 
Eight - 8
Five -  5
Four - 4
One - 1
Seven - 7
Two - 2
Three - 3
Values and Keys after sorting 
One - 1
Two - 2
Three - 3
Four - 4
Five - 5
Seven - 7
Eight - 8






你可能感兴趣的:(面试宝典,java,hashmap,数据结构,面试,java)