Dave's Brain

Browse - Programming Tips - A HashMap randomizes the order of keys. How can I keep keys in add order?

Date: 2013jun20
Language: Java
Keywords: LinkedHashSet, insert

Q.  A HashMap randomizes the order of keys.  How can I keep keys in add order?

A.  Use LinkedHashMap.
The entrySet() will be in the same order as they keys were added.
(Not necessarily alphabetical order)

I used this class when I wanted to read the section of a .ini file
in.  And then write it out with a small change but not radically
changing the order of the keys.

LinkedHashMap<String,String> map = new LinkedHashMap<String,String>(); map.put("One", "1"); map.put("Two", "2"); map.put("Three", "3"); for (String key : map.entrySet()) { System.out.println(key); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.