【问题标题】:How to get and print a specific same value to entry in HashMap [closed]如何获取和打印特定的相同值以在 HashMap 中输入 [关闭]
【发布时间】:2017-09-05 13:17:42
【问题描述】:

例如,我的 HashMap 下面有键(整数)和值(整数):

HashMap <Integer, Integer> mymap = new HasHmap <> ();
mymap.put(1, 3);
mymap.put(2, 4);
mymap.put(3, 1);
mymap.put(4, 5);
mymap.put(5, 2);

打印输出:match found! [1,3] [3,1]

是否可以在我的 HashMap 中找到并打印这样的匹配项?你能教我怎么做吗?

【问题讨论】:

  • 您到底想要达到什么目的?请添加一些您尝试过的代码
  • 嗯,是的,这是可能的。看看API

标签: java hash hashmap


【解决方案1】:

是的,很简单:

// loop over every entry
for (Entry<Integer, Integer> entry : mymap.entrySet()) {
    // look up for current value, and check if it is equal to the key
    if (mymap.get(entry.getValue()).equals(entry.getKey())) {
        // it's a match!
        System.out.println("[" + entry.getKey() + ", " + entry.getValue() + "]");
        // stop after first match (asked in comments)
        break;
    }
}

这将输出:

[1, 3]

【讨论】:

  • 好的,这更干净了,谢谢 :D,如果我有超过 1 个匹配项,我只想打印找到的第一个匹配项怎么办?
  • 只需添加一个break 语句,查看我编辑的答案。
  • @RYREN 为什么它不再被接受?另一种速度较慢(3 次查找而不是 1 次),包含无用代码,并且针对对象使用 ==,即 wrong
  • 是的,先生,确实更快,谢谢,但是当我尝试将给定的 entryKeys 设置为 userinput = 0 时,它显示为 null
  • @RYREN 抱歉,我不明白您遇到了什么问题,以及如果我的失败,其他解决方案会如何工作。请您再解释一下吗?
【解决方案2】:

这是代码,但您可以使用类似的方法解决问题。

输出是

1 -> 3

3 -> 1

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

class GfG {
    public static void main(String[] args) {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(1, 3);
        map.put(2, 3);
        map.put(5, 3);
        map.put(3, 1);
        map.put(6, 3);
        Set<Entry<Integer, Integer>> entry = map.entrySet();
        for(Entry<Integer, Integer> e: entry){
            int key = e.getKey();
            int value = e.getValue();
            if(map.containsKey(value) && map.get(value) != null && map.get(value) == key){
                System.out.println(key +" -> "+value);
            }
        }
    }
}

【讨论】:

  • 非常感谢!!虽然我理解流程,但你能解释一下 Set = HashMap.entrySet();和 if() 语句的条件,我只是在 Hashmap 的学习曲线中:D
猜你喜欢
  • 2020-10-26
  • 2022-01-09
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
相关资源
最近更新 更多