Filtering a list of JavaBeans with Google Guava

前端 未结 9 761
夕颜
夕颜 2020-12-01 06:59

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

9条回答
  •  感动是毒
    2020-12-01 07:09

    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:

    • old-school way (like @Louis wrote)
    • verbose Guava filter (@JB's answer)
    • or other functional Java libraries (@superfav's answer).

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

提交回复
热议问题