0
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.

1
  • You have to create a new set for each iteration, not one set for all iterations. If you would have debugged your code, you would have seen that you keep constantly writing to the same set. Commented May 26, 2014 at 9:32

3 Answers 3

4

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()));
}
Sign up to request clarification or add additional context in comments.

Comments

3

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);
   }

Comments

0

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.