【发布时间】:2019-01-11 14:26:55
【问题描述】:
我正在尝试从另一个 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");
我需要一个具有这种格式的新地图:
a->fb->fd->fe->fk->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;
}
【问题讨论】:
-
能不能把目前制作的地图贴出来,这样更容易发现你的问题
-
@Lino 如果我们有 ("a","b") 和某处 ("b","d"),我们只需将键“a”重定向到值“d”跨度>
-
您的问题和代码不清楚。除了
a->f、b->f等之外,重新映射键和值的实际规则是什么? -
不,我的意思是您当前代码的输出。例如。运行代码时打印的内容
-
@JustinAlbano 这是一个 HashMap;因此键的顺序是不可预测的。
标签: java dictionary hashmap