有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将hashmap值交换为键

我有一个哈希图

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

我的要求是构建一个新的hashmap,旧映射中的值作为键,键作为值列表。 新的hasmap看起来像

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

共 (2) 个答案

  1. # 1 楼答案

    我重新创建了你的例子,这应该是你想要的。如果对代码有任何其他问题,请告诉我

    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);
            }
        });
    
  2. # 2 楼答案

    假设你有一个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);