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

huangapple 未分类评论53阅读模式
英文:

How can I get two keys with duplicate values and print it?

问题

Sure, here's the translated content:

  1. 我有一个针对 **LinkedHashMap** 的方法 `getKeyFromValue`我想从该映射的值中获取键我如何获取具有重复值的两个键并像这样打印出来
  2. System.out.print( getKeyFromValue(hashmap, value1), getKeyFromValue(hashmap, value2) )
  3. key1 = 1key2 = 2
  4. value1 = value2 = 1
  5. private static Object getKeyFromValue(Map hm, Object value) {
  6. for (Object o : hm.keySet()) {
  7. if (hm.get(o).equals(value)) {
  8. return o;
  9. }
  10. }
  11. return null;
  12. }
英文:

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

  1. System.out.print( getKeyFromValue(hashmap, value1), getKeyFromValue(hashmap, value2) )
  2. key1 = 1, key2 = 2
  3. value1 = value2 = 1
  4. private static Object getKeyFromValue(Map hm, Object value) {
  5. for (Object o : hm.keySet()) {
  6. if (hm.get(o).equals(value)) {
  7. return o;
  8. }
  9. }
  10. return null;
  11. }

答案1

得分: 0

你需要一个名为getKeysFromValue()的方法,并使其返回一个包含键的arrayList

  1. key1 = 1key2 = 2
  2. value1 = value2 = 1
  3. /* 将键值对放入映射中 */
  4. private static List<Object> getKeysFromValue(Map hm, Object value) {
  5. List<Object> rtn = new ArrayList<>();
  6. for (Object o : hm.keySet()) {
  7. if (hm.get(o).equals(value)) {
  8. rtn.add(o);
  9. }
  10. }
  11. return rtn;
  12. }
英文:

You would need a method getKeysFromValue() and have it return an array or a List of the keys.

  1. key1 = 1, key2 = 2
  2. value1 = value2 = 1

/* put the key - values into the map */

  1. private static List&lt;Object&gt; getKeysFromValue(Map hm, Object value) {
  2. List&lt;Object&gt; rtn = new ArrayList&lt;&gt;();
  3. for (Object o : hm.keySet()) {
  4. if (hm.get(o).equals(value)) {
  5. rtn.add(o);
  6. }
  7. }
  8. return rtn;
  9. }

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

发表评论

匿名网友

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

确定