Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
Haman Singh Avatar asked Feb 11 '26 15:02

Haman Singh


1 Answers

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());
like image 199
Deadpool Avatar answered Feb 14 '26 12:02

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!