Noorus Khan
Noorus Khan

Reputation: 1476

Confusion regarding map and linked hashmap

I have this confusion in my mind regarding LinkedHashMap. In Set we do not have any key value pair, so when we try to print the set element, we will not get the order preserved for printing element as we have inserted, means order is not preserved, but when we are using LinkedHashSet, this will assure that order will be preserved, as we have inserted the element in linked hash set, while printing we will get the same order. This make sense.

But in case of Map, we print the values using key only, so what is the logic in saying that LinkedHashMap preserves order? We're supposed to print the values using key, so wherever the key-value pair is, the key will print its value. It has to go to map and search for that key and finally print its value.

I hope you will be able to get my question..

Upvotes: 2

Views: 182

Answers (4)

biziclop
biziclop

Reputation: 49754

Apart from the methods already mentioned, you can also use map.forEach() to iterate across your map entries in insertion order.

Upvotes: 0

kushal bajaj
kushal bajaj

Reputation: 73

First of all you can access the values of map without using keys, you can use values method.and all depends on the scenario.

Upvotes: 2

Eran
Eran

Reputation: 393846

so what is the logic in saying that linked hash map preserve order

LinkedHashMap preserves (by default) the order in which the keys were first inserted to the Map. You can iterate over the keys using keySet or over the entries using entrySet in order to get the keys/entries in this order.

Upvotes: 3

Pratik
Pratik

Reputation: 954

When you iterate map it will manage your order in linked Hash Map.

It is not like that you always get values using key only. you need to get all elements from the Map and you may not aware about it. for example - creating Select Drop down using map.

for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

Upvotes: 3

Related Questions