Home > OS >  Compare HashMap values and return first key
Compare HashMap values and return first key

Time:08-13

I've got HashMap

Map<String, Integer> map = new HashMap<>();
        map.put("b", 2);
        map.put("a", 2);
        map.put("c", 2);

I need to compare values, and if it equals, I need to return first key value "b", but map return "a".

How can I achieve it?

CodePudding user response:

In HashMap, keys are not ordered, so you cannot tell which key was first inserted.

Have a look at LinkedHashMap for a Map with ordered keys.

CodePudding user response:

Hashmaps are not designed to search for values (i.e, they are designed to search for keys). You may want to create a different hashmap for this:

Map<Integer, ArrayList<String>> map2 = new HashMap<>();
ArrayList<String> arr = new ArrayList<>();
arr.add("b");
arr.add("a");
arr.add("c");
map2.put(2, arr);
map2.get(2).get(0); // returns "b", i.e, first element added into the array
  • Related