[Java] How to sort HashMap by key/value?

First comes a small question (>_<) to
 
give an integer array, count the frequency of each number, and sort in the order of increasing number of appearances. If the number of appearances is the same, sort according to the increasing order of the number itself.
 
input: [5, 2, 3, 3, 1, 3, 4, 2, 5, 2, 3, 5]

output: [[1, 1], [4, 1], [2, 3], [5, 3], [3, 4]]

 

The statistical frequency directly uses HashMap, but:

HashMap is unordered, there is no Comparator available for rewriting (Comparator)

 
There is a clever idea:

Place the elements of the Map, the Entry<K, V> object, into the List. So you can use the sorting method of Collections and pass in the rewritten comparator.

 
The specific code is:

List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());

Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
    
    
	@Override
	public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
    
    
        if (o1.getValue() != o2.getValue()) {
    
    
        	return o1.getValue() - o2.getValue();
        } else {
    
    
        	return o1.getKey() - o2.getKey();
        }
    }
});

Guess you like

Origin blog.csdn.net/m0_46202073/article/details/114491895