HelloWorld HelloWorld - 2 months ago 19
Java Question

unable to fetch set from map using java8

what I'm trying to do

Set<A> set=new HashSet();
Map<String,List<String>> map=new HashMap();
if(map.keySet().contains("key"){
for(String str: map.get("key")
{
for(A a : listOfA)
{
if(a.getString().equalsIgnoreCase(str);
set.add(a);
}
}

}


What I tried

if(map.keySet().contains("key")
{
listOfA
.stream()
.filter(t->t.getString().equalsIgnoreCase(map.get("key")
.stream
.flatMap(c->c.toString()))
.distinct()
.collect(Collectors.toSet()):

}



//error The method equalsIgnoreCase(String) in the type String is not
applicable for the arguments (Stream)


if(map.keySet().contains("key")
{
map.get("key").stream().filter(t->t.equals(listOfA.stream().map(a->a.getString()))).collect(Collectors.toSet());
}


and this method returns Set<
String
>,obviously as output but I want Set<
A
> as output


so how to solve this, using functional programming

Answer

You can check if any String of map.get("key") is equalsIgnoreCase to getString() of a given A instance by streaming map.get("key") and using anyMatch :

List<String> value = map.get("key");
Set<A> set = null;
if (value != null) {
   set = listOfA.stream()
                .filter(a->value.stream()
                                .anyMatch(s->a.getString().equalsIgnoreCase(s)))
                .collect(Collectors.toSet());
}