I'd like to find objects in a list based on having a certain property.
For example, say I have a list of objects of this class:
class Person {
private String name;
private String id;
}
I know that I can get all of the names of people in the list by using:
Collection<String> names = CollectionUtils.collect(
personList,
TransformerUtils.invokerTransformer("getName"));
but what I want to do is get a list of the Person objects whose name is, for example, "Nick". I don't have Java 8.
I see you are using Apache Common Utils, then you can use:
CollectionUtils.filter( personList, new Predicate<Person>() {
@Override
public boolean evaluate( Person p ) {
return p.getName() != null && p.getName().equals( "Nick" );
}
});
If you don't want to use Java 8 streams, simply loop through the list and check the elements manually:
ArrayList<Person> filteredList = new ArrayList<Person>();
for(Person person : personList) {
if(person.getName().equals("Nick")) filteredList.add(person);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With