-1

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

2 Answers2

3
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);
        }
Vlad L
  • 1,544
  • 3
  • 6
  • 20
0

You must use LinkedHashMap data structure for ordered key.