[英]Compare HashMap values and return first key
I've got HashMap
我有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"
.我需要比较值,如果相等,我需要返回第一个键值"b"
,但 map 返回"a"
。
How can I achieve it?我怎样才能实现它?
In HashMap
, keys are not ordered, so you cannot tell which key was first inserted.在HashMap
中,键没有排序,因此您无法分辨哪个键首先插入。
Have a look at LinkedHashMap
for a Map with ordered keys.查看带有有序键的 Map 的LinkedHashMap
。
Hashmaps are not designed to search for values (ie, they are designed to search for keys ). Hashmaps 不是为搜索值而设计的(即,它们是为搜索键而设计的)。 You may want to create a different hashmap for this:您可能需要为此创建一个不同的 hashmap:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.