2

This is the first time that I have to order an HashMap in Java. I need to do that by key but in my case the key is an object so I need to order by a specific field. Trying to figure it by my own I've considered to proceed with this simple scratch of code:

private HashMap<SimpleDBField, String> sortTable(HashMap<SimpleDBField, String> row){

    LinkedHashMap<SimpleDBField, String> orderedRow = new LinkedHashMap<SimpleDBField, String>();

    for(int i = 1; i <= row.size(); i ++){
        Iterator iterator = row.entrySet().iterator();

        while(iterator.hasNext()){
            Map.Entry<SimpleDBField, String> entry = (Map.Entry<SimpleDBField, String>) iterator.next();

            if(entry.getKey().getListPosition()==i){
                orderedRow.put(entry.getKey(), entry.getValue());
                break;
            }
        }
    }

    return orderedRow;
}

Assuming that it works and I don't care about performance, before really use it, I wish to know if the next scratch of code could be better and most important: Why?

Example below source here: How to sort HashMap by key and value in Java

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);

    Map<K,V> sortedMap = new LinkedHashMap<K,V>();

    for(K key: keys){
        sortedMap.put(key, map.get(key));

    }

    return sortedMap;
}

If both are wrong, how should I do that?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Andrea Grimandi
  • 631
  • 2
  • 8
  • 32
  • possible duplicate of [How to sort a HashMap in Java](http://stackoverflow.com/questions/780541/how-to-sort-a-hashmap-in-java) – Murat Karagöz Aug 24 '15 at 08:44
  • You can't do that; by definition a HashMap has no defined order for its keys. Also, do you want insertion order or some natural order (ie, by means of Comparable)? – fge Aug 24 '15 at 08:47
  • Hash collections are always unordered in order to reach the most possible performance of access by key. – Alex Salauyou Aug 24 '15 at 08:47

4 Answers4

6

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);.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
5

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);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Yes, we can use TreeMap.

TreeMap<Foo, Bar> foo = new TreeMap(myHashMap);
Partho63
  • 3,117
  • 2
  • 21
  • 39
ayesha
  • 1
0

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;
}
Abolfazl Hashemi
  • 684
  • 7
  • 21