我试图从另一个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");
Run Code Online (Sandbox Code Playgroud)
我需要一个具有以下格式的新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");
Run Code Online (Sandbox Code Playgroud)
我的代码是,但似乎没有给出真正的结果.
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;
}
Run Code Online (Sandbox Code Playgroud)