user3675769
user3675769

Reputation: 11

how to convert Map<Integer, List<String>> to Map<Integer, Set<String>>

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
        Set<String> set = new TreeSet<>();
        for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
            set.addAll(entry.getValue());
            mapSet.put(entry.getKey(), set);
        }

It doesnt work. I want to copy mapList to mapSet.

Upvotes: 0

Views: 379

Answers (3)

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32478

You can convert a List to Set using HashSet's constructor like, new HashSet<String>(myList);

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();

   for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
        Set<String> set = new HashSet<String>(entry.getValue());
        mapSet.put(entry.getKey(), set);
   }

Upvotes: 3

Alexis C.
Alexis C.

Reputation: 93872

You keep adding and modifying the same object for all the keys.

What you currently do can be viewed as this:

enter image description here

So to fix that, create a new Set at each iteration of the loop.

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
    Set<String> set = new TreeSet<>();
    set.addAll(entry.getValue());
    mapSet.put(entry.getKey(), set);
}

Also you could use the constructor that takes a collection as parameter.

Map<Integer, List<String>> mapList = new TreeMap<>();
Map<Integer, Set<String>> mapSet = new TreeMap<>();
for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
    mapSet.put(entry.getKey(), new TreeSet<>(entry.getValue()));
}

Upvotes: 4

Aniket Thakur
Aniket Thakur

Reputation: 68975

Add Set in your for loop

    for (Map.Entry<Integer, List<String>> entry : entriesSortedByValues(mapList)) {
        Set<String> set = new TreeSet<>();
        set.addAll(entry.getValue());
        mapSet.put(entry.getKey(), set);
    }

Upvotes: 0

Related Questions