我想根据谓词筛选java.util.Collection。
当前回答
谷歌的Guava库中的Collections2.filter(Collection,Predicate)方法正是您所寻找的。
其他回答
一些简单明了的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()是静态导入的
使用集合查询引擎(CQEngine)。这是目前为止最快的方法。
请参见:如何在Java中查询对象集合(Criteria/SQL-like)?
这里有一些非常棒的答案。对我来说,我想让事情尽可能简单易懂:
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();
}
}
}
}
}
从Java 8的早期发行版开始,你可以尝试这样做:
Collection<T> collection = ...;
Stream<T> stream = collection.stream().filter(...);
例如,如果你有一个整数列表,你想过滤> 10的数字,然后将这些数字打印到控制台,你可以这样做:
List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);
numbers.stream().filter(n -> n > 10).forEach(System.out::println);
使用来自Apache Commons的CollectionUtils.filter(Collection,Predicate)。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 如何检查IEnumerable是否为空或空?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder