Compile error: cannot convert Set<Set<T>> to Set<Map.Entry<T, Set<T>>>

Haman Singh :

I am new to with streams, I want to modify the map by applying stream operations to its entry set but I was unable to do it due to compile error.

The code below simply creates a new map object and assign some integer values to it. Then it attempts to modify the map by removing ones by applying stream operations on its entry set and assigns it to another set.

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

class Example {
public static void main (String[] args) {
    Map<Integer, Set<Integer>> map = new HashMap<>();

    map.put(1, new HashSet<>());
    map.put(2, new HashSet<>());
    map.put(3, new HashSet<>());

    for (int i = 1; i <= 3; ++i)
        for (int j = 1; j <= 3; ++j)
            map.get(i).add(j);

    Set<Map.Entry<Integer, Set<Integer>>> set = map.entrySet().stream()
                                                              .filter(e -> !e.equals(1))
                                                              .map(e -> e.setValue(e.getValue().stream()
                                                                                               .filter(x -> !x.equals(1))
                                                                                               .collect(Collectors.toSet())))
                                                              .collect(Collectors.toSet());
    System.out.println(set);
    }
 }

The code above gave compile errors, I don't know why because the way I looked at it, it looks fine. What to change in my code above to compile successfully?

Deadpool :

1) Filter entries in Map which keys are not equals to 1 (Since Map will not allow duplicate keys you will have only one entry with key 1)

2) And the filter the Set (Since Set will not allow duplicates will have only one value of 1)

Set<Map.Entry<Integer,Set<Integer>>> result =  map.entrySet()
                                                  .stream()
                                                  .filter(e->!e.getKey().equals(1))
                                                  .map(entry->new AbstractMap.SimpleEntry<Integer, Set<Integer>>(entry.getKey(),entry.getValue().stream().filter(i->!i.equals(1)).collect(Collectors.toSet())))
                                           .collect(Collectors.toSet());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=100763&siteId=1
set
set