1

I'm trying to copy the keys and values from one map, map1, into another map, map2. The values in map 1 are stored in a set and map 2 should store map1's values in a list. The keys in each should map the same in both maps.

I could loop through the keys in map1 then add those keys to map 2. And have another inner for loop to add each set's elements to the list in map2 but I'm not sure if this is a right way to go about it, or even correct.

public static <K, V> void changeSetToList (Map<K, Set<V>> map1, Map<K, List<V>> map2) {
for (Map.entry<K, Set<V>> entry : m1.keys()) 
  for (List<V> l : m1.values()) 
      m2.put(entry.getKey(), l.getValue());

}

I haven't compiled or tested it yet though. No access to computer.

4
  • You need to be clear about the problem. The problem is copying data from a set to map. Important information is execution context and design decision. Why you want to copy a set to map? is the set already populated? when you can iterate over the complete set, why you want to copy the data to a map? Oct 8, 2012 at 8:19
  • Did you try map2.putAll(map1) ?
    – user902383
    Oct 8, 2012 at 8:22
  • You can try using List.addAll(Collections<?>) method... That takes a collection, and create a copy of that...
    – Rohit Jain
    Oct 8, 2012 at 8:24
  • @user902383.. That will not the convert the Set into List..
    – Rohit Jain
    Oct 8, 2012 at 8:28

1 Answer 1

1

You can iterate through the Map and use new ArrayList(Collections) constructor to create a List out of the Set stored in original Map.. And put it into new Map..

    Map<String, Set<String>> givenMap = new HashMap<String, Set<String>>();
    Map<String, List<String>> newMap = new HashMap<String, List<String>>();

    Set<String> newSet = new HashSet<String>();
    newSet.add("rohit");

    givenMap.put("a", newSet);
    givenMap.put("b", newSet);
    givenMap.put("c", newSet);

    for (String str: givenMap.keySet()) {
        newMap.put(str, new ArrayList<String>(givenMap.get(str)));
    }

    for(String str:newMap.keySet()) {
        System.out.println(newMap.get(str));
    }

And if you want to use a Generic method.. You need to change your method to this: -

public static <K, V> void changeSetToList (Map<K, Set<V>> givenMap, 
        Map<K, List<V>> newMap) {

    for (K str: givenMap.keySet()) {
        newMap.put(str, new ArrayList<V>(givenMap.get(str)));
    }

    for(K str:newMap.keySet()) {
        System.out.println(newMap.get(str));
    }
}
1
  • Whoop nvm. Works great. Thanks.
    – nitiger
    Oct 8, 2012 at 8:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.