Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will hashmap.keyset() return keys in the order they were added to the hashmap?

Tags:

java

I know that the .keySet() returns a set, which is un-ordered.

As far as I can tell, that means I need to keep an array list of keys in order to track the order in which the keys were added to the hashmap, correct?

like image 530
bernie2436 Avatar asked Mar 13 '12 19:03

bernie2436


People also ask

Does map keySet maintain order?

A map's keySet function returns a Set and the set's iterator method says this in its documentation: "Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)."

Is keySet of HashMap ordered?

As we know that Hash map in Java does not maintain insertion order either by key or by order. Also it does not maintain any other order while adding entries to it.

What does HashMap keySet return?

keySet. Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

Is keySet sorted?

The keySet() method of SortedMap Interface in Java is used to create a set out of the key elements contained in the treemap. It basically returns a set view of the keys or we can create a new set and store the key elements in them in an ascending order.


1 Answers

[...] that means I need to keep an array list of keys in order to track the order in which the keys were added to the hashmap, correct?

Yes, that's correct. Or, you could use a LinkedHashMap which does this for you.

From the documentation:

[...] This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). [...]

like image 73
aioobe Avatar answered Nov 15 '22 00:11

aioobe