我有两个哈希映射。首先是
Map<String, ArrayList<String>> name = new HashMap<String, ArrayList<String>>();
其中包含名称作为键,城市作为值。第二是
Map<String, ArrayList<String>> games = new HashMap<String, ArrayList<String>>();
其中包含城市作为关键字,以及每个城市的游戏列表作为值。
所以,我想比较城市,如果城市匹配,那么我想将作为值的游戏列表分配为名称作为关键。即我需要一个哈希映射,它将名称作为键,并将游戏列表作为值。
我真的需要一些帮助,所以请提供详细信息,因为我是Java的初学者。
先谢谢
答案 0 :(得分:1)
我认为第一张地图应该包含名称作为键,城市作为值而不是城市列表。
通过以下假设,代码可以正常工作
Map<String, ArrayList<String>> nameGameListMap= new HashMap<String, ArrayList<String>>();
Iterator<String> it = name.keySet().iterator();
while(it.hasNext())
{
String name = it.next();
String city = name.get(name);
if(games.containsKey(city))
{
nameGameListMap.put(name, games.get(city));
}
}
答案 1 :(得分:0)
试试这个
Map<String, List<String>> name = new HashMap<String, List<String>>();
List<String> name1CityList = new ArrayList<String>();
name1CityList.add("city1");
name1CityList.add("city2");
List<String> name2CityList = new ArrayList<String>();
name2CityList.add("city2");
List<String> name3CityList = new ArrayList<String>();
name3CityList.add("city3");
name3CityList.add("city4");
name.put("name1", name1CityList);
name.put("name2", name2CityList);
name.put("name3", name3CityList);
Map<String, List<String>> games = new HashMap<String, List<String>>();
List<String> city1GameList = new ArrayList<String>();
city1GameList.add("game1");
city1GameList.add("game2");
city1GameList.add("game3");
List<String> city2GameList = new ArrayList<String>();
city2GameList.add("game1");
city2GameList.add("game2");
List<String> city3GameList = new ArrayList<String>();
city3GameList.add("game2");
city3GameList.add("game3");
games.put("city1", city1GameList);
games.put("city2", city2GameList);
games.put("city2", city3GameList);
Map<String, List<String>> namegames = new HashMap<String, List<String>>();
List<String> tempList;
for (Map.Entry<String, List<String>> entry : name.entrySet()) {
tempList = new ArrayList<String>();
for (String str : entry.getValue()) {
for (Map.Entry<String, List<String>> entry_new : games.entrySet()) {
if (str.equals(entry_new.getKey())) {
for(String str_new : entry_new.getValue()){
tempList.add(str_new);
}
}
}
}
if(!tempList.isEmpty()){
namegames.put(entry.getKey(), tempList);
}
tempList = null;
}
for (Map.Entry<String, List<String>> entry : namegames.entrySet()) {
for(String str : entry.getValue()){
System.out.println("Name : "+entry.getKey()+" Game :"+str);
}
}