我在比较两个arraylist时遇到问题,
我的第一个arraylist看起来像这样:
{TeamID=4, Group=A, TeamName=Germany}
{TeamID=6, Group=A, TeamName=Turkey}
我的第二个清单:
{TeamID=4, Chance=99.9%}
{TeamID=6, Chance=38.4%}
然后我想创建一个列表,如下所示:
{TeamID=4, Group=A, TeamName=Germany Chance=99.9%}
{TeamID=6, Group=A, TeamName=Turkey Chance=38.4%}
你能帮助我吗?
第一份清单:
private ArrayList<HashMap<String, String>> TeamList = this.xml.TeamListList;
第二
private ArrayList<HashMap<String, String>> QChanceList = this.xml.QChanceListList;
答案 0 :(得分:1)
团队列表应该是地图的地图。使用团队ID作为外部地图中的关键字(如果您不想更改为数据库)。
合并条目将非常容易。迭代机会列表,从团队地图中获取团队,并使用teamMap.putAll(mapFromChanceList)
编辑:以示例更新。
Map<String, Map<String, String> teams = new HashMap<String, Map<String, String>();
Map<String, String> team = new Map<String, String>();
//populate the team map, and with TeamID, TeamName etc, then do something like this.
teams.put(team.get("TeamID"), team);
//You get a team by doing:
Map<String, String> team = teams.get(teamId); //where teamId is e.g. "4"
答案 1 :(得分:1)
这是一个想法。对于每个团队,我在机会列表中搜索相应的条目,然后我将两个地图中的所有条目都放入一个新的。
public static List<Map<String, String>> merge(
List<Map<String, String>> teams, List<Map<String, String>> chances) {
// create the result
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
// now we assume that for each team there is one chance (valid?)
for (Map<String, String> team:teams) {
boolean success = false;
Map<String, String> combined = new HashMap<String, String>();
combined.putAll(team);
String id = team.get("TeamID");
// now we have to find the "chance" map
for (Map<String, String> chance:chances) {
if (chance.get("TeamID").equals(id)) {
combined.putAll(chance);
boolean success = true;
break;
}
}
if (!success) {
// there was no entry in chances map with this id!! -> handle problem
}
result.add(combined);
}
return result;
}
(这个例子不是非常安全,它断言,所有地图都有“TeamId”的值,我只是证明在非法输入的情况下必须要做的事情,比如不完整的机会清单)
答案 2 :(得分:0)
与Andreas_D类似,这是另一种皮肤猫的方法。
我想说我仍然同意Dori,这看起来确实像数据库数据。我建议你使用一个数据库,省去解决已经解决的问题的头痛。
或者使用您正在使用的API的所有者来获取此数据并让他们使用正确的数据库查询在它到达您之前合并它。
放弃这一点,你最好的办法是做这样的事情来达到这一点,这样你就可以使用hashmap的实用程序了。
....
HashMap<String, HashMap<String, String>> unifiedMap = new HashMap<String, HashMap<String, String>>();
for (HashMap<String, String> teamMap : teamList) {
String teamId = teamMap.get("TeamID");
HashMap<String, String> mapFromUnified = unifiedMap.get(teamId);
if (mapFromUnified == null) {
unifiedMap.put(teamId, teamMap);
} else {
for (String key : teamMap.keySet()) {
// this will be a race condition, the last one in wins - good luck!
mapFromUnified.put(key, teamMap.get(key));
}
}
}
for (HashMap<String, String> teamMap : chanceList) {
String teamId = teamMap.get("TeamID");
HashMap<String, String> mapFromUnified = unifiedMap.get(teamId);
if (mapFromUnified == null) {
unifiedMap.put(teamId, teamMap);
} else {
for (String key : teamMap.keySet()) {
// this will be a race condition, the last one in wins - good luck!
mapFromUnified.put(key, teamMap.get(key));
}
}
}
....