Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find elements in a collection by property?

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.

like image 651
Mahmoud Saleh Avatar asked Jun 11 '12 12:06

Mahmoud Saleh


People also ask

How can we access elements of a collection?

Java provides Iterator and ListIterator classes to retrieve the elements of the collection object. The hasNext() method of these interfaces returns true if the collection object has next element else it returns false. The next() methods of the Iterator and ListIterator returns the next element of the collection.

How to find element in Stream Java?

To find an element matching specific criteria in a given list, we: invoke stream() on the list. call the filter() method with a proper Predicate. call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.

How to see if a list contains a value c#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.


1 Answers

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"));
like image 73
Francisco Spaeth Avatar answered Nov 09 '22 00:11

Francisco Spaeth