Here you can find the source of sortByKeys(Map
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map)
//package com.java2s; //License from project: Open Source License import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Main { public static <K extends Comparable, V extends Comparable> Map<K, V> sortByKeys(Map<K, V> map) { List<K> keys = new LinkedList<K>(map.keySet()); Collections.sort(keys);//from ww w . j a v a2s . c o m //LinkedHashMap will keep the keys in the order they are inserted //which is currently sorted on natural ordering Map<K, V> sortedMap = new LinkedHashMap<K, V>(); for (K key : keys) { sortedMap.put(key, map.get(key)); } return sortedMap; } }