Search code examples
javahashmap

Java HashMap sorted by key insertion time - creative order


I want to sort hashmap or add all keys to arraylist by creative order For example:

        HashMap<String, String> map_from_file = new HashMap<String, String>();
        map_from_file.put("C", "c");
        map_from_file.put("B", "b");
        map_from_file.put("D", "d");
        map_from_file.put("A", "a");


        for (String key : map_from_file.keySet()) {
            System.out.println(key);
        }

Output:

A
B
C
D

I want the output to be:

C
B
D
A

Thank's for any help


Solution

  • Map<String, String> map_from_file = new LinkedHashMap<>();
            map_from_file.put("C", "c");
            map_from_file.put("B", "b");
            map_from_file.put("D", "d");
            map_from_file.put("A", "a");
    
    
            for (String key : map_from_file.keySet()) {
                System.out.println(key);
            }