i have simple java 8 example using filter. When i try to filter , getting empty value.
class Per {
String id;
Per(String id) {
this.id = id;
}
public String getId() {
return id;
}
public static void main(String[] args) {
List<String> allIds = new ArrayList<>();
allIds.add("1");
allIds.add("2");
allIds.add("3");
allIds.add("4");
List<Per> unavailableItems = new ArrayList<>();
unavailableItems.add(new Per("2"));
unavailableItems.add(new Per("4"));
List<Per> ids = unavailableItems.stream().filter(per -> !(allIds.contains(per.getId())))
.collect(Collectors.toList());
System.out.println(ids);// why its returning empty value
}
}
Why am getting empty value.Please help any one
>Solution :
Read filter as:
"Should I include (filter) this item, yes or no"
So when your code does the following:
List<Per> ids = unavailableItems.stream().filter(per -> !(allIds.contains(per.getId())))
Then your code checking if it should remove the item Per("2")
And the logic is "if allIds has a "2"? then no, don’t filter it, don’t include it (that’s the ! in your code)
And indeed, you’re not including it.
Then repeats with Per("4") and you don’t include it either.
The result of not including the two elements is an empty lis.
I hope this helps to clarify it.
Probably you think "filter" means, "filter out" or "exclude" but is the opposite.
It seems to me that you’re trying to do the opposite, filter from allIds those elements that are in unavailableItems
In that case:
List<String> allAvailable = allIds.stream().filter( id -> {
for (Per p : unavailableItems) {
if ( p.getId().equals(id)) {
return false;
}
}
return true;
}).collect(Collectors.toList());
System.out.println(allAvailable);
Does exactly what you need and prints:
[1, 3]