What is the best way to filter a Java Collection?

2018-12-31 01:58发布

I want to filter a java.util.Collection based on a predicate.

27条回答
流年柔荑漫光年
2楼-- · 2018-12-31 02:16

With Guava:

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
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 02:17

The setup:

public interface Predicate<T> {
  public boolean filter(T t);
}

void filterCollection(Collection<T> col, Predicate<T> predicate) {
  for (Iterator i = col.iterator(); i.hasNext();) {
    T obj = i.next();
    if (predicate.filter(obj)) {
      i.remove();
    }
  }
}

The usage:

List<MyObject> myList = ...;
filterCollection(myList, new Predicate<MyObject>() {
  public boolean filter(MyObject obj) {
    return obj.shouldFilter();
  }
});
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 02:17

How about some plain and straighforward Java

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

Simple, readable and easy (and works in Android!) But if you're using Java 8 you can do it in a sweet one line:

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

Note that toList() is statically imported

查看更多
公子世无双
5楼-- · 2018-12-31 02:18

The Collections2.filter(Collection,Predicate) method in Google's Guava library does just what you're looking for.

查看更多
人间绝色
6楼-- · 2018-12-31 02:18
不再属于我。
7楼-- · 2018-12-31 02:18

Some really great great answers here. Me, I'd like to keep thins as simple and readable as possible:

public abstract class AbstractFilter<T> {

    /**
     * Method that returns whether an item is to be included or not.
     * @param item an item from the given collection.
     * @return true if this item is to be included in the collection, false in case it has to be removed.
     */
    protected abstract boolean excludeItem(T item);

    public void filter(Collection<T> collection) {
        if (CollectionUtils.isNotEmpty(collection)) {
            Iterator<T> iterator = collection.iterator();
            while (iterator.hasNext()) {
                if (excludeItem(iterator.next())) {
                    iterator.remove();
                }
            }
        }
    }
}
查看更多
登录 后发表回答