我想根据谓词筛选java.util.Collection。
当前回答
在我的情况下,我正在寻找与特定字段空排除列表。 这可以用for循环来完成,并填充没有空地址的对象的临时列表。 但是多亏了Java 8流
List<Person> personsList = persons.stream()
.filter(p -> p.getAdrress() != null).collect(Collectors.toList());
#java #集合#集合#java8 #流
其他回答
这里有一些非常棒的答案。对我来说,我想让事情尽可能简单易懂:
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();
}
}
}
}
}
使用来自Apache Commons的CollectionUtils.filter(Collection,Predicate)。
考虑使用支持泛型的更新的Collections框架谷歌Collections。
更新:谷歌集合库现在已弃用。你应该使用最新发布的番石榴。它仍然具有对集合框架的所有相同扩展,包括基于谓词进行筛选的机制。
Java 8(2014)在一行代码中使用流和lambdas解决了这个问题:
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)));
你能想象出更有可读性的东西吗?
免责声明:我是lambdaj的贡献者
“最好”这个要求太宽泛了。它是“最短的”吗?“最快”?“可读”? 过滤器的地方或到另一个集合?
最简单(但不是最易读)的方法是迭代它,并使用Iterator.remove()方法:
Iterator<Foo> it = col.iterator();
while( it.hasNext() ) {
Foo foo = it.next();
if( !condition(foo) ) it.remove();
}
现在,为了使其更具可读性,可以将其包装到实用程序方法中。然后发明一个IPredicate接口,创建该接口的匿名实现,并执行如下操作:
CollectionUtils.filterInPlace(col,
new IPredicate<Foo>(){
public boolean keepIt(Foo foo) {
return foo.isBar();
}
});
where filterInPlace()迭代集合并调用Predicate.keepIt()来了解实例是否保留在集合中。
我真的没有看到为这项任务引入第三方库的正当理由。
推荐文章
- 在流中使用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