博士 MZA:
私はいくつかの値が他のエントリでキーとなる別の地図から新しい地図を作成しようとしています。
例:
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->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
与えられたが、チェーン内の最後の値であり、
あなたはこのようなメソッドを呼び出すことができます。
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;
}