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

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

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 中,给定的键不能有多个值。值需要是一个列表或另一个可以容纳多个值的对象类型。

  1. String search = "Mexico";
  2. // 创建 TreeMap
  3. Map<String, String> stateMap = new TreeMap();
  4. stateMap.put("CO", "USA");
  5. stateMap.put("Ontario", "Canada");
  6. stateMap.put("Chiapas", "Mexico");
  7. stateMap.put("Chihuahua", "Mexico");
  8. stateMap.put("TX", "USA");
  9. stateMap.put("GA", "USA");
  10. // HashSet 将存储在搜索国家中找到的唯一状态列表
  11. Set<String> results = new HashSet();
  12. // 遍历源 TreeMap,寻找与搜索字符串匹配的国家
  13. for (String state : stateMap.keySet()) {
  14. String country = stateMap.get(state);
  15. if (country.equals(search)) {
  16. results.add(state);
  17. }
  18. }
  19. // 遍历结果集并打印搜索国家的每个状态
  20. 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.

  1. String search = &quot;Mexico&quot;;
  2. // create our TreeMap
  3. Map&lt;String, String&gt; stateMap = new TreeMap();
  4. stateMap.put(&quot;CO&quot;, &quot;USA&quot;);
  5. stateMap.put(&quot;Ontario&quot;, &quot;Canada&quot;);
  6. stateMap.put(&quot;Chiapas&quot;, &quot;Mexico&quot;);
  7. stateMap.put(&quot;Chihuahua&quot;, &quot;Mexico&quot;);
  8. stateMap.put(&quot;TX&quot;, &quot;USA&quot;);
  9. stateMap.put(&quot;GA&quot;, &quot;USA&quot;);
  10. // HashSet will store the unique list of states found in the search country
  11. Set&lt;String&gt; results = new HashSet();
  12. // iterate over the source TreeMap looking for the country to match the search string
  13. for (String state : stateMap.keySet()) {
  14. String country = stateMap.get(state);
  15. if (country.equals(search)) {
  16. results.add(state);
  17. }
  18. }
  19. // iterate through the results set and print each state for the search country
  20. results.forEach(state -&gt; System.out.println(state));
  21. </details>

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

发表评论

匿名网友

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

确定