Reputation:
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
Upvotes: 3
Views: 97
Reputation: 298469
The following solution might scale better if your listOfA
is rather large:
List<String> value = map.getOrDefault("key", Collections.emptyList());
Collection<String> c;
if(value.isEmpty()) c=value;
else { c=new TreeSet<>(String.CASE_INSENSITIVE_ORDER); c.addAll(value); }
Set<A> set = listOfA.stream()
.filter(a->c.contains(a.getString()))
.collect(Collectors.toSet());
Upvotes: 2
Reputation: 393986
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());
}
Upvotes: 4