HashMap排序--Java8

curlykale發表於2018-04-26
package com.nyis.zf.test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapSortTest {
	
	public static void main(String[] args) {  
		 Map<String, Integer> unsortMap = new HashMap<>();
	        unsortMap.put("z", 10);
	        unsortMap.put("b", 5);
	        unsortMap.put("a", 6);
	        unsortMap.put("c", 20);
	        unsortMap.put("d", 1);
	        unsortMap.put("e", 7);
	        unsortMap.put("y", 8);
	        unsortMap.put("n", 99);
	        unsortMap.put("j", 50);
	        unsortMap.put("m", 2);
	        unsortMap.put("f", 9);

	        System.out.println("Original...");
	        System.out.println(unsortMap);

	        Map<String, Integer> result = sortMapByValue(unsortMap);

	        System.out.println("Sorted...");
	        System.out.println(result);
    }
	
	public static Map<String, Integer> sortMapBykey(Map<String, Integer> unsortMap){
		Map<String, Integer> result = new LinkedHashMap<>();
		//sort by key, a,b,c..., and put it into the "result" map
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        return result;
	}
	
	public static Map<String, Integer> sortMapByValue(Map<String, Integer> unsortMap){
		Map<String, Integer> result = new LinkedHashMap<>();
		//sort by value, and reserve, 10,9,8,7,6...
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())  // reversed倒序,不指定型別,會預設為<java.util.Map.Entry<java.lang.Object,V>>
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        return result;
	}

}

複製程式碼

參考連結

https://www.cnblogs.com/yucfeng/p/8794608.html

相關文章