减少某些条目中键是值的映射

Dr.*_*Mza 2 java dictionary hashmap

我试图从另一个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)

Lin*_*ica 10

您可以通过辅助函数中的一些简单递归逻辑来实现:

public static String findCorrespondingValue(Map<String, String> map, String key){
    if(map.containsKey(key)){
        return findCorrespondingValue(map, map.get(key));
    }
    return key;
}
Run Code Online (Sandbox Code Playgroud)

如上所述逻辑非常简单,我们只检查给定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())
    );
}
Run Code Online (Sandbox Code Playgroud)

或者如果你碰巧使用java 8:

Map<String, String> result = testMap.entrySet().stream()
    .collect(Collectors.toMap(
        e -> e.getKey(),  // or just Map.Entry::getKey
        e -> findCorrespondingValue(e.getValue())
     ));
Run Code Online (Sandbox Code Playgroud)

你当然必须实现某种逻辑来确定你是否有循环引用.例如:

a -> b
b -> f
f -> a
Run Code Online (Sandbox Code Playgroud)

哪个目前只是失败了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;
}
Run Code Online (Sandbox Code Playgroud)