如何过滤 Java 集合(基于谓词)? [英] How to filter a Java Collection (based on predicate)?
本文介绍了如何过滤 Java 集合(基于谓词)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据谓词过滤 java.util.Collection
.
推荐答案
Java 8 (2014) 在一行代码中使用流和 lambdas 解决了这个问题:
Java 8 (2014) solves this problem using streams and lambdas in one line of code:
List<Person> beerDrinkers = persons.stream()
.filter(p -> p.getAge() > 16).collect(Collectors.toList());
这是一个 教程.
使用 Collection#removeIf
就地修改集合.(注意:在这种情况下,谓词将删除满足谓词的对象):
Use Collection#removeIf
to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):
persons.removeIf(p -> p.getAge() <= 16);
<小时>
lambdaj 允许在不编写循环或内部类的情况下过滤集合:
lambdaj allows filtering collections without writing loops or inner classes:
List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
greaterThan(16)));
你能想象出更具可读性的东西吗?
Can you imagine something more readable?
免责声明:我是 lambdaj 的贡献者
Disclaimer: I am a contributor on lambdaj
这篇关于如何过滤 Java 集合(基于谓词)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文