-1

I'm trying to sort HashMap's output using LinkedHashMapand TreeMap.

When I use TreeMap to sort out HashMap it works like a charm.

        Map<Integer, String> hMap = new HashMap<Integer, String>();

        hMap.put(40, "d");
        hMap.put(10, "a");
        hMap.put(30, "c");
        hMap.put(20, "b");

        System.out.println(" ");
        System.out.println("before");

        for (Map.Entry m1 : hMap.entrySet()) {
            System.out.print(m1.getKey() + " " + m1.getValue() + "    ");
        }

        System.out.println("after");

        Map<Integer, String> hTree = new TreeMap<Integer, String>(hMap);
        for (Map.Entry m2 : hTree.entrySet()) {
            System.out.print(m2.getKey() + " " + m2.getValue() + "    ");
        }

Output :
before 20 b 40 d 10 a 30 c
after 10 a 20 b 30 c 40 d

But when I try with LinkedHashMap to sort HashMap it doesn't seems to work.

        Map<Integer, String> hMap = new HashMap<Integer, String>();

        hMap.put(10, "a");
        hMap.put(20, "b");
        hMap.put(30, "c");
        hMap.put(40, "d");

        System.out.println("before");

        for (Map.Entry m1 : hMap.entrySet()) {
            System.out.print(m1.getKey() + " " + m1.getValue() + "    ");
        }
        System.out.println(" ");
        System.out.println("after");

        LinkedHashMap<Integer, String> lhMap = new LinkedHashMap<Integer, String>(hMap);

        Iterator it = lhMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry me = (Map.Entry) it.next();
            System.out.print(me.getKey() + " " + me.getValue()+"   ");
        }

Output :

before
20 b    40 d    10 a    30 c     
after
20 b   40 d   10 a   30 c  

Can anyone tell me why is this sorting doesn't work? Is that becuase LinkedHashMap is filtering the HashMap?
If it is why TreeMap is immune to that issue?
Thank you

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Dil.
  • 1,996
  • 7
  • 41
  • 68
  • 5
    What gave you the impression that a `LinkedHashMap` sorts anything? – Sotirios Delimanolis Sep 12 '18 at 06:19
  • @SotiriosDelimanolis it sort through insertion order. – Dil. Sep 12 '18 at 06:20
  • 3
    And you got the insertion order as output. – LuCio Sep 12 '18 at 06:20
  • @LuCio. No it is not. Insertion order is `10,20,30,40`. Output is `20,40,10,30`. Please take a look at the second example – Dil. Sep 12 '18 at 06:23
  • 4
    @pippilongstocking that's the insertion order into the HashMap. Not the insertion order into the LinkedHashMap. You pass a HashMap to the LinkedHashMap constructor. So this constructor iterates though the HashMap (which has no ordering), and inserts each element of the HashMap into the LinkedHashMap. And as you see, you get the same order as in the HashMap, which shows that the insertion order is preserved. – JB Nizet Sep 12 '18 at 06:28

5 Answers5

7

LinkedHashMap maintains the insertion order. This means that if you pass to the constructor a sorted Map, or put the keys in the LinkedHashMap in sorted order, it will remain sorted.

However, you pass a HashMap to the LinkedHashMap constructor, and it's not sorted (since HashMap has no ordering). Therefore the resulting LinkedHashMap is also not ordered.

On the other hand, TreeMap keeps the keys sorted, so the order in which you put the keys in the TreeMap (which in your example is determined by the order the keys are encountered while iterating over the source HashMap) doesn't matter - the resulting Map will always be sorted.

Eran
  • 387,369
  • 54
  • 702
  • 768
6

The JavaDoc of LinkedHashMap says:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

By creating the LinkedHashMap by inserting a HashMap, the LinkedHashMap preserves the order of the HashMap hMap.

The JavaDoc of the HashMap says:

This class makes no guarantees as to the order of the map; in particular,

Thus the not guaranteed order of the HashMap hMap is preserved by LinkedHashMap lhMap.

On the other hand you created the TreeMap hTree using the default constructor. That means you created "a new, empty tree map, using the natural ordering of its keys.". Therefore hTree is sorted on every insertion. An insertion implies an ordering.

Regarding the LinkedHashMap it does no ordering on its own.


Further reading: Sorting LinkedHashMap

LuCio
  • 5,055
  • 2
  • 18
  • 34
5

1) Treemap will sort the element by using natural order by default.

2) Linkedhasmap will maintain the insertion order like list.

arjunan
  • 217
  • 1
  • 9
3

TreeMap sorts by the compareTo implemented by keys (or a comparator function passed on construction, comparing keys). LinkedHashMap only keeps order of insertion so I guess when you create it using a hash map the insertion order is the same as when you iterate over the HashMap.

Roy Shahaf
  • 494
  • 5
  • 10
0

HashMap doesn't keep the sort for the keys. What's more, note that it's not guarded that an HashMap instance shows the (k-v) sequences identically when it's size changes due to the load factor.

The "sort" means for LinkedHashMap is not about the sort by key value comparison. Instead, it means the insert order or the access order.

insert order <2,"A">, <1,"B"> ,<3,"C">

iterate order as insert order: <2,"A">, <1,"B"> ,<3,"C">

Then assume that implementing operation of accessing(get/put) <1,"B"> iterate order as access order: <2,"A">, <3,"C">,<1,"B">

Sunny
  • 129
  • 1
  • 3