如何获取具有重复值的两个键并将其打印?

huangapple go评论139阅读模式
英文:

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 = 1key2 = 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()的方法,并使其返回一个包含键的arrayList

key1 = 1key2 = 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&lt;Object&gt; getKeysFromValue(Map hm, Object value) {
    List&lt;Object&gt; rtn = new ArrayList&lt;&gt;();
    for (Object o : hm.keySet()) {
        if (hm.get(o).equals(value)) {
            rtn.add(o);
        }
    }
    return rtn;
}

huangapple
  • 本文由 发表于 2020年3月15日 12:22:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/60689728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定