Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a list of JavaBeans with Google Guava

Tags:

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?

like image 728
Or Peles Avatar asked Dec 26 '11 14:12

Or Peles


1 Answers

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.

like image 200
Louis Wasserman Avatar answered Mar 06 '23 07:03

Louis Wasserman