我创建了一个使用字符串作为键和整数作为值的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=[维也纳,萨尔茨堡]}
的结果。
我尝试了以下方法。这是一种不太优雅的方法,而且并没有给出正确的结果。
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=[科隆], 41=[因特拉肯], 43=[萨尔茨堡]}
。请问有人能告诉我正确的方法来实现这个结果吗?注:我知道可以使用MultiMap来实现,但我们只能使用Java Collection Framework而不能使用Java 8。