List< Person> filtered = Lists.newArrayList(); (Person p:allPersons){
if(acceptedNames.contains(p.getName())){
filtered.add(p);
$ b你可以用Guava做到这一点,但是Java不是' t Python,并试图将其转化为Python,只会使难以理解且不可读的代码永久存在。番石榴的功能性应用应该谨慎使用,只有当它们为代码或性能提供具体和可测量的益处时。
In a Java program, I have a list of beans that I want to filter based on a specific property.
For example, say I have a list of Person, a JavaBean, where Person has many properties, among them 'name'.
I also have a list of names.
Now I want to find all the persons whose name is in the name list.
What is the best way to execute this filter using Google Guava?
So far, I've thought about combining Guava with Apache beanutils, but that doesn't seem elegant.
I've also found a reflection extension library here: http://code.google.com/p/guava-reflection/, but I'm not sure how to use it (there's little documentation).
Any thoughts?
p.s. Can you tell I really miss Python list comprehension?
解决方案
Do it the old-fashioned way, without Guava. (Speaking as a Guava developer.)
List<Person> filtered = Lists.newArrayList();
for(Person p : allPersons) {
if(acceptedNames.contains(p.getName())) {
filtered.add(p);
}
}
You can do this with Guava, but Java isn't Python, and trying to make it into Python is just going to perpetuate awkward and unreadable code. Guava's functional utilities should be used sparingly, and only when they provide a concrete and measurable benefit to either lines of code or performance.
这篇关于用Google Guava过滤JavaBeans列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!