天天看點

過濾Java集合的最佳方法是什麼

過濾Java集合的最佳方法是什麼?

我想過濾java.util.Collection基于謂詞的。

高分回答:

Java 8(2014)在一行代碼中使用流和lambda解決了此問題:

List<Person> beerDrinkers = persons.stream()
    .filter(p -> p.getAge() > 16).collect(Collectors.toList());      

這是一個教程。

用于Collection#removeIf在适當位置修改集合。(注意:在這種情況下,謂詞将删除滿足該謂詞的對象):

persons.removeIf(p -> p.getAge() <= 16);      

lambdaj允許過濾集合而無需編寫循環或内部類:

List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
    greaterThan(16)));      

您能想象一些更具可讀性的東西嗎?

高分回答:

假設您使用的是Java 1.5,并且無法添加Google Collections,那麼我将執行與Google員工非常相似的操作。這與喬恩的評論略有不同。

首先将此接口添加到您的代碼庫中。

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

當某個謂詞為某種類型的真時,其實作者可以回答。例如,如果T是User和AuthorizedUserPredicate實施IPredicate,則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);      
文章翻譯自kgs4h5t57thfb6iyuz6dqtun5y-ac4c6men2g7xr2a-stackoverflow-com.translate.goog/questions/1…

作者建議:第一條回答,是lambada的開發人員回答的,我推薦用流處理方式來實作