Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract values from a list of objects based on a property of these objects?

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.

like image 486
Nick Div Avatar asked Dec 07 '25 07:12

Nick Div


2 Answers

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" );
    }
});
like image 145
SomeDude Avatar answered Dec 09 '25 19:12

SomeDude


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);
}
like image 31
TimoStaudinger Avatar answered Dec 09 '25 20:12

TimoStaudinger