Reputation: 11
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
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
Reputation: 93872
You keep adding and modifying the same object for all the keys.
What you currently do can be viewed as this:
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
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