-1
import java.util.*;
// import java.io.*;

class test {
    public static void main(String[] args) {
        HashMap<String, Integer> map1 = new HashMap<String, Integer>();
        HashMap<Integer, String> map2 = new HashMap<Integer, String>();
        map1.put("Code", 1);
        map1.put("Amit", 2);
        map1.put("Better", 4);
        map1.put("Coding", 5);
        map2.put(1, "Test");
        map2.put(2, "Kumar");
        map2.put(3, "Ghai");
        map2.put(4, "Coding");
        test t = new test();
        t.HashMapCQ2(map1, map2);
    }

    public void HashMapCQ2(HashMap<String, Integer> map1, HashMap<Integer, String> map2) {
        HashMap<String, String> out = new HashMap<String, String>();
        for (String str : map1.keySet())
            if (map2.containsKey(map1.get(str)))
                out.put(str, map2.get(map1.get(str)));
        System.out.println(out);
    }
}

The expected order would be {Code=Test, Amit=Kumar, Better=Coding}

But I am getting {Better=Coding, Amit=Kumar, Code=Test}.

Does HashMap order the list according to some criteria?

Shubham Goel
  • 1
  • 1
  • 2

1 Answers1

-1

HashMaps in Java are not ordered. There are alternative Maps which preserve the order. Have a look at the following question, which already has answers: Java Ordered Map