Best way to order an HashMap by key in Java?

限于喜欢 提交于 2019-12-01 13:09:45

You cannot control a HashMap's ordering, as you've seen. A LinkedHashMap is just a HashMap with a predictable iteration order - it's a step in the right direction, but it's still over-complicating things. Java has a built-in interface for sorted maps (with the unsurprising name SortedMap), and a couple of implementation, the most popular one being a TreeMap. Just use it and let Java do all the heavy lifting:

public static <K extends Comparable, V> Map<K,V> sortByKeys(Map<K,V> map) {
    return new TreeMap<>(map);
}

Best way is to use a TreeMap.

TreeMap<Foo, Bar> foo = new TreeMap(myHashMap);

If you need a custom comparator, you can use the new TreeMap(Comparator c) and then add the contents of the HashMap there with foo.putAll(myMap);.

yes ,

we can use TreeMap.

TreeMap foo = new TreeMap(myHashMap);

In java8, you can use following code:

    public static <K extends Comparable, V> Map<K,V> sortMapByKey(Map<K, V> unsortedMap) {
    Map<K, V> sortedMap = new LinkedHashMap<>();

    unsortedMap.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByKey())
            .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
    return sortedMap;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!