i’m really new in Java. I would like to make something for a REST services.
I have an array list of an object contains data, i would like to remove all object that don’t match a criteria based on enum.
I get some sample with the Apache CollectionUtils and filter. but all i found is related to an equals value.
at the moment, this is the code i’ve done
MyObjectFiltered.addAll(ListedMyObject);
CollectionUtils.filter(MyObjectFiltered, new Predicate() {
@Override
public boolean evaluate(Object object) {
boolean boolFound = false;
for(String EnumItem : EnumAsList)
{
boolFound = ((MyObjectModel) object).getValue() == EnumItem ;
}
return boolFound;
}
});
I know that’s not the way to do what i want but i can’t figure how i can do it. Do you guys have any suggestion i can search to reach my goal?
Thanks for your help.
2
Answers
This is what the java stream API is for. https://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html
If I understand you correctly, you simply want to remove objects from the list that don’t match a certain Enum? You won’t need an external library for something that simple, Java 8’s lambdas can do that for you.
You just need something along the lines of
MyObjectFiltered.removeIf(object -> !EnumAsList.contains(object.getValue());
Basically that means remove the object from my list if the enums list does not contain it.