Java tutorial
//package com.java2s; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Main { public static <K, V> Map<K, V> sortMapByKey(Map<K, V> map, final Boolean asc) { List<Entry<K, V>> entries = new LinkedList<Entry<K, V>>(map.entrySet()); Collections.sort(entries, new Comparator<Entry<K, V>>() { @SuppressWarnings("unchecked") public int compare(Entry<K, V> o1, Entry<K, V> o2) { if (asc) { return ((Comparable<K>) o1.getKey()).compareTo(o2.getKey()); } else { return -((Comparable<K>) o1.getKey()).compareTo(o2.getKey()); } } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Entry<K, V> entry : entries) { result.put(entry.getKey(), entry.getValue()); } return result; } }