Here you can find the source of sortByKey(T map, final boolean descending)
public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map, final boolean descending)
//package com.java2s; //License from project: Open Source License import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Main { public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map) { return sortByKey(map, false); }//from w w w. j av a2 s . c om public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map, final boolean descending) { return sort(map, new Comparator<Map.Entry<K, V>>() { @Override public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return ((o1.getKey()).compareTo(o2.getKey()) * (descending ? -1 : 1)); } }); } public static <K, V, T extends Map<K, V>> T sort(T map, Comparator<Map.Entry<K, V>> c) { List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, c); Object result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { ((T) result).put(entry.getKey(), entry.getValue()); } return (T) result; } }