1. 程式人生 > 其它 >Sort Map by Value in Java

Sort Map by Value in Java

實際專案或者業務當中,經常會有需求要求對 hashmap 按值排序,並返回指定順序的 TopN 個元素,今天就來分享下具體的程式碼及其原理實現。

package com.bj.test.top10;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;

public class SortMapByValue {

	// output the values is descending
	public static <K, V extends Comparable<? super V>> List<Entry<K, V>> sortMapByValuesTopN(Map<K, V> map, int topN) {

		List<Entry<K, V>> sortedEntries = new ArrayList<Entry<K, V>>(map.entrySet());

		Collections.sort(sortedEntries, new Comparator<Entry<K, V>>() {
			@Override
			public int compare(Entry<K, V> e1, Entry<K, V> e2) {
				return e2.getValue().compareTo(e1.getValue());
			}
		});

		int listLen = sortedEntries.size();
		// System.out.println(listLen);
		while (topN > 0 && listLen > topN) {
			listLen--;
			sortedEntries.remove(listLen);
		}
		return sortedEntries;
	}

	// output the values is descending
	public static <K, V extends Comparable<? super V>> List<Entry<K, V>> sortMapByValues(Map<K, V> map) {

		List<Entry<K, V>> sortedEntries = new ArrayList<Entry<K, V>>(map.entrySet());

		Collections.sort(sortedEntries, new Comparator<Entry<K, V>>() {
			@Override
			public int compare(Entry<K, V> e1, Entry<K, V> e2) {
				return e2.getValue().compareTo(e1.getValue());
			}
		});

		return sortedEntries;
	}

	public static void printMap(Map<String, Integer> map) {
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
		}
	}

	public static Map list2Map(List list) {
		// Convert sorted map back to a Map
		Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
			Map.Entry<String, Integer> entry = it.next();
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}

	public static void main(String[] args) {

		// NavigableMap descMap = new TreeMap<>().descendingMap();
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("A", 34);
		map.put("B", 25);
		map.put("C", 50);
		map.put("D", 50); // "duplicate" value
		map.put("z", 10);
		map.put("b", 5);
		map.put("a", 6);
		map.put("c", 20);
		map.put("d", 1);
		map.put("e", 7);
		map.put("y", 8);
		map.put("n", 99);
		map.put("j", 50);
		map.put("m", 2);
		map.put("f", 9);

		System.out.println("返回前 10 個 value 最大的鍵值對:");
		printMap(list2Map(sortMapByValuesTopN(map, 10)));
		System.out.println(sortMapByValuesTopN(map, 10));
		System.out.println(list2Map(sortMapByValuesTopN(map, 10)).get("n"));

		System.out.println("++++++++++++++++++++++++++++++++++++++n");
		System.out.println("返回排序之後的鍵值對:");
		printMap(list2Map(sortMapByValues(map)));
	}
}



// 結果:
返回前 10 個 value 最大的鍵值對:
[Key] : n [Value] : 99
[Key] : C [Value] : 50
[Key] : D [Value] : 50
[Key] : j [Value] : 50
[Key] : A [Value] : 34
[Key] : B [Value] : 25
[Key] : c [Value] : 20
[Key] : z [Value] : 10
[Key] : f [Value] : 9
[Key] : y [Value] : 8
[n=99, C=50, D=50, j=50, A=34, B=25, c=20, z=10, f=9, y=8]
99
++++++++++++++++++++++++++++++++++++++

返回排序之後的鍵值對:
[Key] : n [Value] : 99
[Key] : C [Value] : 50
[Key] : D [Value] : 50
[Key] : j [Value] : 50
[Key] : A [Value] : 34
[Key] : B [Value] : 25
[Key] : c [Value] : 20
[Key] : z [Value] : 10
[Key] : f [Value] : 9
[Key] : y [Value] : 8
[Key] : e [Value] : 7
[Key] : a [Value] : 6
[Key] : b [Value] : 5
[Key] : m [Value] : 2
[Key] : d [Value] : 1

Refer:

[1] Sort map by value

http://www.leveluplunch.com/java/examples/sort-order-map-by-values/

[2] How to sort a Map in Java

http://www.mkyong.com/java/how-to-sort-a-map-in-java/

[3] Sort a Map<Key, Value> by values (Java)

http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java

    Sorting the Map<Key,Value> in descending order based on the value [duplicate]

http://stackoverflow.com/questions/11647889/sorting-the-mapkey-value-in-descending-order-based-on-the-value