map自定義排序,根據鍵或者值排隊

浪丶蕩發表於2018-12-16

核心比較器
比較器之根據鍵排序

package cn.com.hongyitech.accountsystem.utils;

import java.util.Comparator;

class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String key1, String key2) {
        
        return key1.compareTo(key2);
    }
}

比較器之根據值排序

package cn.com.hongyitech.accountsystem.utils;

import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;

class MapValueComparator implements Comparator<Map.Entry<String, String>> {

	@Override
	public int compare(Entry<String, String> map1, Entry<String, String> map2) {

		return map1.getValue().compareTo(map2.getValue());
	}
}

根據鍵排序

/**
	 * 使用 Map按key進行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, String> sortMapByKey(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}

		Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());

		sortMap.putAll(map);

		return sortMap;
	}

根據值排序

/**
	 * 使用 Map按value進行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new LinkedHashMap<String, String>();
		List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
		Collections.sort(entryList, new MapValueComparator());

		Iterator<Map.Entry<String, String>> iter = entryList.iterator();
		Map.Entry<String, String> tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

測試用例


public static void main(String[] args) {

		Map<String, String> map = new TreeMap<String, String>();

		map.put("2018-12-06", "1");
		map.put("2018-12-03", "2");
		map.put("2018-12-07", "4");
		map.put("2018-12-04", "2");
		map.put("2018-12-01", "3");

		Map<String, String> resultMapByKey = sortMapByKey(map); // 按Key進行排序
		Map<String, String> resultMapByValue = sortMapByValue(map); // 按Value進行排序

		for (Map.Entry<String, String> entry : resultMapByKey.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
		System.out.println("******上面根據key*********************下面根據value********");
		for (Map.Entry<String, String> entry : resultMapByValue.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}

結果

2018-12-01 3
2018-12-03 2
2018-12-04 2
2018-12-06 1
2018-12-07 4
******上面根據key*********************下面根據value********
2018-12-06 1
2018-12-03 2
2018-12-04 2
2018-12-01 3
2018-12-07 4

相關文章