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
Explaining your doubts from the sentence:
So far, I've thought about combining Guava with Apache beanutils, but that doesn't seem elegant.
Java, despite of being so popular, lacks first-class function support*, what is subject to change in Java 8, where you will be able to do:
Iterable filtered = filter(allPersons, (Person p) -> acceptedNames.contains(p.getName()));
With lambdas and it will be elegant.
Until then you have choose between:
I'd also like to add to @Lois's answer that Guava-way would be to create immutable collection, because they are better than unmodifiable, which is also described in Item 15, Minimize mutability in Effective Java by Joshua Bloch**:
ImmutableList.Builder builder = ImmutableList.builder();
for (final Person p : allPersons) {
if (acceptedNames.contains(p.getName())) {
builder.add(p);
}
}
ImmutableList filtered = builder.build();
(It's implementation detail that ImmutableList.Builder creates temporary ArrayList under the hood).
*: it bothers me much, I came from Python, JavaScript and Perl worlds, where functions are treated better
**: Guava and Bloch are tightly coupled in many ways ;)