获取JAVA中树图中唯一值的所有键

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

Fetching all keys for unique value in treemap in JAVA

问题

我有一个树图,其中以国家为值,相应的州/省为键,使得键是唯一的,而值是重复的。我想通过传递特定的国家来获取所有键(即我想获取该国家的所有州/省)。我该如何做到这一点?如果需要提供其他任何信息,请告诉我。

英文:

I have a treemap which has countries as values and corresponding states as keys such that keys are unique and values are duplicate. I want to fetch all keys for a unique value (i.e. I want to fetch all the states of a country by passing that particular country). How do I do that? Let me know if I need to provide any other information.

答案1

得分: 0

这里是一些代码,希望能帮助你开始。从你的帖子中可以观察到,在 Map 中,给定的键不能有多个值。值需要是一个列表或另一个可以容纳多个值的对象类型。

String search = "Mexico";

// 创建 TreeMap
Map<String, String> stateMap = new TreeMap();
stateMap.put("CO", "USA");
stateMap.put("Ontario", "Canada");
stateMap.put("Chiapas", "Mexico");
stateMap.put("Chihuahua", "Mexico");
stateMap.put("TX", "USA");
stateMap.put("GA", "USA");

// HashSet 将存储在搜索国家中找到的唯一状态列表
Set<String> results = new HashSet();

// 遍历源 TreeMap,寻找与搜索字符串匹配的国家
for (String state : stateMap.keySet()) {
   String country = stateMap.get(state);
   if (country.equals(search)) {
      results.add(state);
   }
}

// 遍历结果集并打印搜索国家的每个状态
results.forEach(state -> System.out.println(state));
英文:

Here is some code that will hopefully get you going. One observation from your post is that you cannot have more than one value for a given key in a Map. The value would need to be a list or another object type that can hold multiple values.

String search = &quot;Mexico&quot;;

// create our TreeMap
Map&lt;String, String&gt; stateMap = new TreeMap();
stateMap.put(&quot;CO&quot;, &quot;USA&quot;);
stateMap.put(&quot;Ontario&quot;, &quot;Canada&quot;);
stateMap.put(&quot;Chiapas&quot;, &quot;Mexico&quot;);
stateMap.put(&quot;Chihuahua&quot;, &quot;Mexico&quot;);
stateMap.put(&quot;TX&quot;, &quot;USA&quot;);
stateMap.put(&quot;GA&quot;, &quot;USA&quot;);

// HashSet will store the unique list of states found in the search country
Set&lt;String&gt; results = new HashSet();

// iterate over the source TreeMap looking for the country to match the search string
for (String state : stateMap.keySet()) {
   String country = stateMap.get(state);
   if (country.equals(search)) {
      results.add(state);
   }
}

// iterate through the results set and print each state for the search country
results.forEach(state -&gt; System.out.println(state));

</details>



huangapple
  • 本文由 发表于 2020年4月4日 20:39:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61028204.html
匿名

发表评论

匿名网友

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

确定