javajava-7

How to invert a Map<String, ArrayList<String>> in Java?


I have a map with "task(s)": ["epochdate1", "epochdate2"] how can I reverse (invert) this map?

For example

task_1 => [date1, date2, date3, date5]
task_2 => [date4, date5]
task_3 => [date2, date3, date5]
task_4 => [date4, date5]

when reversed it will be

date1 => [task_1]
date2 => [task_1, task_3]
date3 => [task_1, task_3]
date4 => [task_2, task_4]
date5 => [task_1, task_2, task_3, task_4]

Code

public static void main(String[] args) {
    Map<String, ArrayList<String>> myMap = new HashMap<String, ArrayList<String>>();
    ArrayList<String> t1List = new ArrayList<String>();
    t1List.add("date1");
    t1List.add("date2");
    t1List.add("date3");
    t1List.add("date5");
    ArrayList<String> t2List = new ArrayList<String>();
    t2List.add("date4");
    t2List.add("date5");
    ArrayList<String> t3List = new ArrayList<String>();
    t3List.add("date2");
    t3List.add("date3");
    t3List.add("date5");
    ArrayList<String> t4List = new ArrayList<String>();
    t4List.add("date4");
    t4List.add("date5");
    myMap.put("task_1", t1List);
    myMap.put("task_2", t2List);
    myMap.put("task_3", t3List);
    myMap.put("task_4", t4List);
    
    Map<String, ArrayList<String>> reversedMap = Test.getReversedMap(myMap);
}

Solution

  • Just implement it:

    Map<String, ArrayList<String>> getReversedMap(Map<String, ArrayList<String>> myMap){
          Map<String, ArrayList<String>> result = new HashMap<>();
          for(String key : myMap.keySet()){
              for(String val : myMap.get(key)){
                  if(!result.containsKey(val)){
                      result.put(val, new ArrayList());
                  }
                  result.get(val).add(key);
              }
          }
          return result;
    }