How to find elements in a collection by property?

44,948

Solution 1

The problem is that iteration in Java is often much simpler and cleaner. Perhaps Java 8's Closures will fix this. ;)

Compare with @Spaeth's solution.

List<String> mixedup = Arrays.asList("A", "0", "B", "C", "1", "D", "F", "3");
List<String> numbersOnlyList = new ArrayList<>();
for (String s : mixedup) {
    try {
        // here you could evaluate you property or field
        Integer.valueOf(s);
        numbersOnlyList.add(s);
    } catch (NumberFormatException ignored) {
    }
}
System.out.println("Results of the iterated List: " + numbersOnlyList);

As you can see it much shorter and more concise.

Solution 2

You could use apache commons collection implementing a Predicate for it.

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html

Sample:

package snippet;

import java.util.Arrays;
import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

public class TestCollection {

    public static class User {

        private String name;

        public User(String name) {
            super();
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User [name=" + name + "]";
        }

    }

    public static void main(String[] args) {
        Collection<User> users = Arrays.asList(new User("User Name 1"), new User("User Name 2"), new User("Another User"));
        Predicate predicate = new Predicate() {

            public boolean evaluate(Object object) {
                return ((User) object).getName().startsWith("User");
            }
        };
        Collection filtered = CollectionUtils.select(users, predicate);
        System.out.println(filtered);
    }
}

A few sample can be found here: http://apachecommonstipsandtricks.blogspot.de/2009/01/examples-of-functors-transformers.html

And if you need something more generic, like inspect a value of a specific field or property you could do something like:

public static class MyPredicate implements Predicate {

    private Object expected;
    private String propertyName;

    public MyPredicate(String propertyName, Object expected) {
        super();
        this.propertyName = propertyName;
        this.expected = expected;
    }

    public boolean evaluate(Object object) {
        try {
            return expected.equals(PropertyUtils.getProperty(object, propertyName));
        } catch (Exception e) {
            return false;
        }
    }

}

That could compare a specific property to a expected value, and the use would be something like:

Collection filtered = CollectionUtils.select(users, new MyPredicate("name", "User Name 2"));

Solution 3

You can use Google guava's filter method to do this. Commons also has a filter method

Solution 4

List<Foo> result = foos.stream()
  .filter(el -> el.x == true)
  .collect(Collectors.toList());

https://www.mkyong.com/java8/java-8-streams-filter-examples/

Solution 5

To achieve this In java, you can Override hashCode and equals methods -

for example

@Override
public int hashCode() {
    return eventId;
}

@Override
public boolean equals(Object obj) {
    if(obj instanceof CompanyTimelineView) {
        CompanyTimelineView new_name = (CompanyTimelineView) obj;
        if(new_name.eventId.intValue() == this.eventId.intValue()){
            return true;
        }
    }
    return false;
}

in this example i have mached eventId integer value. You can use your class and his property here. After this you can use list's contains,indexOf,lastIndexOf and get method to find element in the list. See below.

//tempObj is nothing but an empty object containing the essential properties
//tempObj should posses all the properties that are being compared in equals method.

if(listOfObj.contains(tempObj)){
    return listOfObj.get(listOfObj.indexOf(tempObj));
}
Share:
44,948
Mahmoud Saleh
Author by

Mahmoud Saleh

I am Mahmoud Saleh an Enthusiastic Software Engineer, Computer Science Graduate, Experienced in developing J2EE applications, Currently developing with Spring,JSF,Primefaces,Hibernate,Filenet. Email: [email protected] Linkedin: https://www.linkedin.com/in/mahmoud-saleh-60465545? Upwork: http://www.upwork.com/o/profiles/users/_~012a6a88e04dd2c1ed/

Updated on April 06, 2020

Comments

  • Mahmoud Saleh
    Mahmoud Saleh about 4 years

    I have a list of items, and I want to find a list of items that have the boolean property (field variable) x=true.

    I know that this can be accomplished by iteration, but I was looking for a common method to do that in commons library like Apache Commons.