如何按属性查找集合中的元素?

2022-09-05 00:14:01

我有一个项目列表,我想找到一个具有布尔属性(字段变量)的项目列表。x=true

我知道这可以通过迭代来完成,但我正在寻找一种通用的方法,以便在像Apache Commons这样的共享资源库中做到这一点。


答案 1

您可以使用apache commons集合来实现它的谓词。

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

样本:

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

可以在这里找到一些示例:http://apachecommonstipsandtricks.blogspot.de/2009/01/examples-of-functors-transformers.html

如果您需要更通用的东西,例如检查特定字段或属性的值,则可以执行以下操作:

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

}

这可以将特定属性与预期值进行比较,并且用法类似于:

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

答案 2

问题在于,Java中的迭代通常更简单,更干净。也许Java 8的闭包会解决这个问题。;)

与@Spaeth的解决方案进行比较。

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

如您所见,它更短,更简洁。