英文:
How can I get two keys with duplicate values and print it?
问题
Sure, here's the translated content:
我有一个针对 **LinkedHashMap** 的方法 `getKeyFromValue`,我想从该映射的值中获取键。我如何获取具有重复值的两个键,并像这样打印出来:
System.out.print( getKeyFromValue(hashmap, value1), getKeyFromValue(hashmap, value2) )
key1 = 1,key2 = 2
value1 = value2 = 1
private static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
英文:
I have method getKeyFromValue
for LinkedHashMap and I want to get key from the value of this map. How can I get two keys with duplicate values and print it like
System.out.print( getKeyFromValue(hashmap, value1), getKeyFromValue(hashmap, value2) )
key1 = 1, key2 = 2
value1 = value2 = 1
private static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
答案1
得分: 0
你需要一个名为getKeysFromValue()
的方法,并使其返回一个包含键的array
或List
。
key1 = 1,key2 = 2
value1 = value2 = 1
/* 将键值对放入映射中 */
private static List<Object> getKeysFromValue(Map hm, Object value) {
List<Object> rtn = new ArrayList<>();
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
rtn.add(o);
}
}
return rtn;
}
英文:
You would need a method getKeysFromValue()
and have it return an array
or a List
of the keys.
key1 = 1, key2 = 2
value1 = value2 = 1
/* put the key - values into the map */
private static List<Object> getKeysFromValue(Map hm, Object value) {
List<Object> rtn = new ArrayList<>();
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
rtn.add(o);
}
}
return rtn;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论