将hashmap值交换为键

问题描述 投票:-2回答:2

我有一个哈希图

{
k1 = {v1, v2},
k2 = {v2},
k3 = {v1}
}

并且我的要求是构建一个新的哈希图,其中旧映射中的值作为键,而键作为值列表。新的hasmap看起来像

{
v1 = {k1, k3},
v2 = {k1, k2}
}
java hashmap
2个回答
0
投票

我重新创建了您的示例,这应该可以执行您想要的操作。如果对代码还有其他疑问,请告诉我。

HashMap<String,List<String>> hashMap = new HashMap<>();

    hashMap.put("k1", Arrays.asList("v1","v2"));
    hashMap.put("k2", Arrays.asList("v2"));
    hashMap.put("k3", Arrays.asList("v1"));

    HashMap<String,List<String>> result = new HashMap<>();

    hashMap.forEach((s, strings) ->{
        for (String element : strings){
            List<String> tempList = new ArrayList<>();

            if(result.containsKey(element)){
                tempList = result.get(element);
            }

            tempList.add(s);
            result.put(element, tempList);
        }
    });

0
投票

假设您有Map<String,List<String>> myMap = ...

    Map<String,List<String>> reversed = 
            myMap.values().stream().flatMap(List::stream).distinct()
            .map(v ->  new AbstractMap.SimpleEntry<>(v,
                                    myMap.entrySet().stream()
                                    .filter(e -> e.getValue().contains(v))
                                    .map(Map.Entry::getKey)
                                    .collect(Collectors.toList())))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    System.out.println(reversed);
© www.soinside.com 2019 - 2024. All rights reserved.