Java invert map

前端 未结 8 1330
南旧
南旧 2020-11-30 09:33

I need create inverse map - select unique values and for them find keys. Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not

相关标签:
8条回答
  • 2020-11-30 10:29

    I would give another approach to this problem giving an extra dimension: duplicate values in EntrySet.

    public static void main(String[] args) {
    
        HashMap<Integer, String> s = new HashMap<Integer, String>();
        s.put(1, "Value1");
        s.put(2, "Value2");
        s.put(3, "Value2");
        s.put(4, "Value1");
    
        /*
         * swap goes here
         */
        HashMap<String,List<Integer>> newMap = new HashMap<String, List<Integer>>();
        for (Map.Entry<Integer, String> en : s.entrySet()) {
            System.out.println(en.getKey() + " " + en.getValue());
    
            if(newMap.containsKey(en.getValue())){
                newMap.get(en.getValue()).add(en.getKey());
            } else {
                List<Integer> tmpList = new ArrayList<Integer>();
                tmpList.add(en.getKey());
                newMap.put(en.getValue(), tmpList);
            }
        }
    
        for(Map.Entry<String, List<Integer>> entry: newMap.entrySet()){
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
    

    T result will be that:

    1 Value1
    2 Value2
    3 Value2
    4 Value1
    Value1 [1, 4]
    Value2 [2, 3]

    0 讨论(0)
  • 2020-11-30 10:29

    With Guava

    Multimaps.transformValues(Multimaps.index(map.entrySet(), Map.Entry::getValue),
            Map.Entry::getKey)
    

    You'll get a multimap (basically a map of lists) in return.

    0 讨论(0)
提交回复
热议问题