简体   繁体   中英

Compare HashMap values and return first key

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?

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.

Hashmaps are not designed to search for values (ie, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM