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

Date: 2013jun20 Update: 2025oct2 Language: Java Keywords: LinkedHashSet, insert Q. Java: 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. Full example:
import java.util.LinkedHashMap; class Demo { public static final void main(String[] args) { LinkedHashMap<String,String> map = new LinkedHashMap<String,String>(); map.put("One", "1"); map.put("Two", "2"); map.put("Three", "3"); for (String key : map.keySet()) { System.out.println("key=" + key); } } }
Output:
key=One key=Two key=Three