我想根据谓词筛选java.util.Collection。


当前回答

java8之前的简单解决方案:

ArrayList<Item> filtered = new ArrayList<Item>(); 
for (Item item : items) if (condition(item)) filtered.add(item);

不幸的是,这个解决方案不是完全通用的,它输出的是一个列表,而不是给定集合的类型。此外,在我看来,引入库或编写函数来包装这段代码似乎有些过分,除非条件很复杂,但随后可以为该条件编写函数。

其他回答

一些简单明了的Java代码怎么样

 List<Customer> list ...;
 List<Customer> newList = new ArrayList<>();
 for (Customer c : list){
    if (c.getName().equals("dd")) newList.add(c);
 }

简单、易读、简单(在Android上也适用!) 但如果你使用的是Java 8,你可以用一句简单的话来实现:

List<Customer> newList = list.stream().filter(c -> c.getName().equals("dd")).collect(toList());

注意,toList()是静态导入的

使用java 8,特别是lambda表达式,你可以像下面的例子那样简单:

myProducts.stream().filter(prod -> prod.price>10).collect(Collectors.toList())

其中,对于myProducts集合中的每个产品,如果prodc .price>10,则将该产品添加到新的过滤列表中。

番石榴:

Collection<Integer> collection = Lists.newArrayList(1, 2, 3, 4, 5);

Iterators.removeIf(collection.iterator(), new Predicate<Integer>() {
    @Override
    public boolean apply(Integer i) {
        return i % 2 == 0;
    }
});

System.out.println(collection); // Prints 1, 3, 5

考虑使用支持泛型的更新的Collections框架谷歌Collections。

更新:谷歌集合库现在已弃用。你应该使用最新发布的番石榴。它仍然具有对集合框架的所有相同扩展,包括基于谓词进行筛选的机制。

假设您使用的是Java 1.5,并且不能添加谷歌集合,我将做一些非常类似于谷歌人员所做的事情。这与乔恩的评论略有不同。

首先将该接口添加到代码库中。

public interface IPredicate<T> { boolean apply(T type); }

它的实现者可以回答特定类型的某个谓词何时为真。例如,如果T是User, AuthorizedUserPredicate<User>实现IPredicate<T>,那么AuthorizedUserPredicate#apply返回传入的User是否被授权。

然后在一些实用类中,你可以说

public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
    Collection<T> result = new ArrayList<T>();
    for (T element: target) {
        if (predicate.apply(element)) {
            result.add(element);
        }
    }
    return result;
}

所以,假设你有以上可能的用途

Predicate<User> isAuthorized = new Predicate<User>() {
    public boolean apply(User user) {
        // binds a boolean method in User to a reference
        return user.isAuthorized();
    }
};
// allUsers is a Collection<User>
Collection<User> authorizedUsers = filter(allUsers, isAuthorized);

如果关心线性检查的性能,那么我可能希望有一个具有目标集合的域对象。具有目标集合的域对象将具有用于初始化、添加和设置目标集合的方法的过滤逻辑。

更新:

在实用程序类(假设是Predicate)中,我添加了一个select方法,其中有一个在谓词不返回预期值时用于默认值的选项,还有一个用于在新IPredicate中使用的参数的静态属性。

public class Predicate {
    public static Object predicateParams;

    public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {
        Collection<T> result = new ArrayList<T>();
        for (T element : target) {
            if (predicate.apply(element)) {
                result.add(element);
            }
        }
        return result;
    }

    public static <T> T select(Collection<T> target, IPredicate<T> predicate) {
        T result = null;
        for (T element : target) {
            if (!predicate.apply(element))
                continue;
            result = element;
            break;
        }
        return result;
    }

    public static <T> T select(Collection<T> target, IPredicate<T> predicate, T defaultValue) {
        T result = defaultValue;
        for (T element : target) {
            if (!predicate.apply(element))
                continue;
            result = element;
            break;
        }
        return result;
    }
}

下面的例子查找集合之间缺失的对象:

List<MyTypeA> missingObjects = (List<MyTypeA>) Predicate.filter(myCollectionOfA,
    new IPredicate<MyTypeA>() {
        public boolean apply(MyTypeA objectOfA) {
            Predicate.predicateParams = objectOfA.getName();
            return Predicate.select(myCollectionB, new IPredicate<MyTypeB>() {
                public boolean apply(MyTypeB objectOfB) {
                    return objectOfB.getName().equals(Predicate.predicateParams.toString());
                }
            }) == null;
        }
    });

下面的示例在集合中查找实例,如果找不到实例,则返回集合的第一个元素作为默认值:

MyType myObject = Predicate.select(collectionOfMyType, new IPredicate<MyType>() {
public boolean apply(MyType objectOfMyType) {
    return objectOfMyType.isDefault();
}}, collectionOfMyType.get(0));

更新(Java 8发布后):

自从我(艾伦)第一次发布这个答案已经有好几年了,我仍然不敢相信我的这个答案能获得SO分。无论如何,现在Java 8已经在语言中引入了闭包,我的答案将会有很大的不同,而且更简单。在Java 8中,不需要单独的静态实用程序类。如果你想找到匹配谓词的第一个元素。

final UserService userService = ... // perhaps injected IoC
final Optional<UserModel> userOption = userCollection.stream().filter(u -> {
    boolean isAuthorized = userService.isAuthorized(u);
    return isAuthorized;
}).findFirst();

JDK 8 API的可选功能有get(), isPresent(), orElse(defaultUser), orElseGet(userSupplier)和orElseThrow(exceptionSupplier),以及其他“单体”函数,如map, flatMap和filter。

如果您只想收集与谓词匹配的所有用户,那么使用collector终止所需集合中的流。

final UserService userService = ... // perhaps injected IoC
final List<UserModel> userOption = userCollection.stream().filter(u -> {
    boolean isAuthorized = userService.isAuthorized(u);
    return isAuthorized;
}).collect(Collectors.toList());

有关Java 8流如何工作的更多示例,请参见这里。