英文:
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 = "Mexico";
// create our 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 will store the unique list of states found in the search country
Set<String> 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 -> System.out.println(state));
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论