【发布时间】:2011-11-25 23:58:10
【问题描述】:
在 java 中,如果我有两个对象 A 和 B,并且都包含引用 id 的类变量,并且 A 也有一个类变量类型,则 B 有一个类变量位置。我正在尝试构建一个以键为类型、以值为位置的地图。目前我正在通过构建两个单独的地图来做到这一点,一个地图(Map1)将引用ID链接到类型,并通过迭代A类型的对象列表来构建,另一个地图(Map2)将引用ID链接到位置并构建通过遍历类型 B 的对象列表。然后通过遍历 Map1 的 keySet 并找到引用 id 的值,将其作为键放在新映射中,然后获取位置的值,从而合并映射来自 Map2 并将其用作类型的值。实现如下所示。我的问题是:有没有更有效的方法来做这个算法?这似乎不是最好的实现。很抱歉含糊不清 - 希望代码能让问题更清楚。
Map<String, String> referenceIdToType = new HashMap<String, String>();
Map<String, String> referenceIdToLocation = new HashMap<String, String>();
for(Info info : infoList) {
referenceIdToType.put(info.getReferenceId(), info.getType());
}
for(Location loc : locationList) {
referenceIdToLocation.put(loc.getReferenceId(), loc.getLocation());
}
Map<String, String> typeToLocation = new HashMap<String, String>();
for(String referenceId : referenceIdToType.keySet()) {
typeToLocation.put(referenceIdToType.get(referenceId), referenceIdToLocation.get(referenceId));
}
【问题讨论】: