本文介绍了使用 Google Guava 过滤 JavaBeans 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 程序中,我有一个 bean 列表,我想根据特定属性对其进行过滤.

In a Java program, I have a list of beans that I want to filter based on a specific property.

例如,假设我有一个 Person 列表,一个 JavaBean,其中 Person 有许多属性,其中包括 'name'.

For example, say I have a list of Person, a JavaBean, where Person has many properties, among them 'name'.

我还有一个名字列表.

现在我想找到所有名字在名单中的人.

Now I want to find all the persons whose name is in the name list.

使用 Google Guava 执行此过滤器的最佳方法是什么?

What is the best way to execute this filter using Google Guava?

到目前为止,我已经考虑过将 Guava 与 Apache beanutils 结合使用,但这似乎并不优雅.

So far, I've thought about combining Guava with Apache beanutils, but that doesn't seem elegant.

我还在这里找到了一个反射扩展库:http://code.google.com/p/guava-reflection/,但我不确定如何使用它(文档很少).

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).

有什么想法吗?

附言你能说我真的很怀念 Python 列表理解吗?

p.s. Can you tell I really miss Python list comprehension?

推荐答案

采用老式方法,不用 Guava.(以 Guava 开发人员的身份发言.)

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);
   }
}

您可以使用 Guava 来完成此操作,但 Java 不是 Python,并且尝试将其融入 Python 只会使笨拙且不可读的代码永久化.Guava 的函数式实用程序应该谨慎使用,并且仅当它们为代码行或性能提供具体且可衡量的好处时才使用.

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 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:21