【发布时间】:2017-09-14 12:35:49
【问题描述】:
我创建了一个使用 String 作为键和 Integer 作为值的 Map。所以,就像citiesWithCodes。
到目前为止,出于测试目的,我已手动将值放入 Hashmap 中。它们是:
Map<String, Integer> citiesWithCodes = new HashMap<String, Integer>();
citiesWithCodes.put("Berlin", 49);
citiesWithCodes.put("Frankfurt", 49);
citiesWithCodes.put("Hamburg", 49);
citiesWithCodes.put("Cologne", 49);
citiesWithCodes.put("Salzburg", 43);
citiesWithCodes.put("Vienna", 43);
citiesWithCodes.put("Zurich", 41);
citiesWithCodes.put("Bern", 41);
citiesWithCodes.put("Interlaken", 41);
我想根据城市的代码以列表或数组格式获取城市。因此,例如对于值 43,它应该返回类似 {43=[Vienna, Salzburg]} 的内容。
我尝试了以下方法。这绝对是一种肮脏的方法,并且没有给出正确的结果。
public static Map<Integer, List<String>> codeCities(Map<String, Integer> citiesWithCodes){
Map<Integer, List<String>> segList = new HashMap<Integer, List<String>>();
List<String> city;
Iterator<Entry<String, Integer>> i = citiesWithCodes.entrySet().iterator();
while (i.hasNext()) {
city = new ArrayList<String>();
Entry<String, Integer> next = i.next();
i.remove();
city.add(next.getKey());
for (Entry<String, Integer> e : citiesWithCodes.entrySet()) {
if(e.getValue().equals(next.getValue())){
city.add(e.getKey());
citiesWithCodes.remove(e);
}
}
System.out.println(city);
segList.put(next.getValue(), city);
}
return segList;
}
我得到的输出是:{49=[Cologne], 41=[Interlaken], 43=[Salzburg]}
有人能告诉我,实现结果的正确方法吗?
PS:我知道使用 MultiMap 是可能的。但我们仅限于使用 Java Collection Framework,也不能使用 Java 8。
【问题讨论】:
-
你可以使用 Java 8 吗?
-
@SchiduLuca。不幸的是,项目范围仅限于 Java 7。