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

11,756

Solution 1

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" );
    }
});

Solution 2

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);
}

Solution 3

Using Apache collection utils (which you are already using), you can use the filter method which creates a subset of your collection consisting of items which match a given filter, combined with a Predicate that matches "Nick" based on your Transformer and transformedPredicate:

CollectionUtils.filter(names, PredicateUtils.transformedPredicate(
    TransformerUtils.invokerTransformer("getName"), PredicateUtils.equalPredicate("Nick")));

That said, you may want to reconsider using such a heavily functional approach before you migrate to Java 8. Not only will you have a lot of redundant Apache collections code after you migrate, the solutions prior to the introduction of closures and lambdas tend to be verbose and often less readable than the imperative alternatives.

Note: this modifies the existing collection in-place. If that is not the desired behavior, you'll need to create a copy before calling the filter method.

Share:
11,756
Nick Div
Author by

Nick Div

SOreadytohelp

Updated on June 16, 2022

Comments

  • Nick Div
    Nick Div almost 2 years

    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.