我正在尝试从另一个 map 创建一个新 map ,其中一些值是其他条目中的键。
例子:
HashMap<String,String> testMap = new HashMap<>();
testMap.put("a","b");
testMap.put("b","d");
testMap.put("d","e");
testMap.put("e","f");
testMap.put("k","r");
我需要一个具有这种格式的新 map :
a->f
b->f
d->f
e->f
k->r
producedMap.put("a","f");
producedMap.put("b","f");
producedMap.put("d","f");
producedMap.put("e","f");
producedMap.put("k","r");
我的代码是这样的,但似乎没有给出真正的结果。
public HashMap<String,String> getMatched(HashMap<String,String> correpondanceMap){
Collection<String> correpondanceKeys = correpondanceMap.keySet();
HashMap<String,String> newCorrepondanceMap= new HashMap<>();
correpondanceMap.entrySet().forEach(entry->{
if (correpondanceKeys.contains(entry.getValue())){
String newValue = entry.getValue();
String keyOfnewValue = correpondanceMap
.entrySet()
.stream()
.filter(entriii -> newValue.equals(entry.getValue()))
.map(Map.Entry::getKey).limit(1).collect(Collectors.joining());
newCorrepondanceMap.put(keyOfnewValue,correpondanceMap.get(newValue));
}
else
{
newCorrepondanceMap.put(entry.getKey(),entry.getValue());
}
});
newCorrepondanceMap.entrySet().forEach(entry-> System.out.println(entry.getKey() +" -- > " +entry.getValue()));
return newCorrepondanceMap;
}
最佳答案
您可以通过辅助函数中的一些简单递归逻辑来实现:
public static String findCorrespondingValue(Map<String, String> map, String key){
if(map.containsKey(key)){
return findCorrespondingValue(map, map.get(key));
}
return key;
}
如前所述,逻辑非常简单,我们只是检查对于给定的 key
,给定的 map
中是否存在值
- 如果是,我们将再次执行该函数,但这次使用
value
作为 新的key
。 - 如果不存在映射,我们可以安全地说给定的
key
是最后一个 值(value)链
你可以这样调用方法:
Map<String, String> testMap = ... // setup testMap
Map<String, String> result = new HashMap<>();
for (final Entry<String, String> entry : testMap.entrySet()) {
result.put(
entry.getKey(),
findCorrespondingValue(testMap, entry.getValue())
);
}
或者如果你碰巧使用 java 8:
Map<String, String> result = testMap.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey(), // or just Map.Entry::getKey
e -> findCorrespondingValue(e.getValue())
));
您当然必须实现某种逻辑来查明您是否有循环引用。例如:
a -> b
b -> f
f -> a
当前会因 StackOverflowError
而失败。
如果你想支持多种不同的类型,而不仅仅是 String
,你可以使它也通用:
public static <T> T findCorrespondingValue(Map<? extends T, ? extends T> map, T key){
if(map.containsKey(key)){
return findCorrespondingValue(map, map.get(key));
}
return key;
}
关于java - 减少一个映射,其中键是某些条目中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54148460/