Use map and filter functions to remove elements from a set which exists in a treemap (Java Collections)

user11045864 :

how to use filter function to remove elements from a set which exists in a treemap like this

TreeSet<Integer> set = new TreeSet<>();  
TreeMap<Integer, Integer> map = new TreeMap<>();    
set.removeAll(map.entrySet().stream()
       .filter(x -> x.getValue()>1).collect(Collectors.toList())) ; 

when i ran this it gave me

Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$Entry cannot be cast to java.lang.Comparable
    at java.util.TreeMap.getEntry(Unknown Source)
    at java.util.TreeMap.remove(Unknown Source)
    at java.util.TreeSet.remove(Unknown Source)
    at java.util.AbstractSet.removeAll(Unknown Source)
    at Main.main

so how to solve this ? and how to use them ?

dbl :

The problem with your solution is that you are passing a List<Map.Entry> to the TreeSet::removeAll when it expects an Itterable.

set.removeAll(map.entrySet().stream()
    .filter(x -> x.getValue() > 1)
    .collect(Collectors.toList()));

What you have to do is map each of the filtered items to an integer and collect those instead.

set.removeAll(map.entrySet().stream()
    .filter(x -> x.getValue() > 1)
    .map(Map.Entry::getValue) // get the value itself and collect those instead.
    .collect(Collectors.toList()));

Here is a test performed:

TreeSet<Integer> set = new TreeSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>() {{ 
    put(1, 1); put(2, 2); put(3, 3);
}};

set.removeAll(map.entrySet().stream()
    .filter(x -> x.getValue() > 1)
    .map(Map.Entry::getValue)
    .collect(Collectors.toList()));

System.out.println(set); // prints [1, 4, 5, 6, 7]

Guess you like

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