thurmc
thurmc

Reputation: 525

Guava function to add items to resultant collection based on applying conditions to each item in list

I am trying to create a set of items by looking through an existing set and adding each one to a resultant list if it meets certain conditions. I was wondering if there was a more efficient way to do this task using some of the Google Guava libraries. The algorithm is below

    final List<String> matchingItems = new ArrayList<>();
    for (final String li : getItems()) {
        if (li.length() > 5) {
            matchingItems.add(li);
        }
    }
    return matchingItems;

Upvotes: 0

Views: 243

Answers (1)

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35427

No

There are no more efficient way to write that for-loop than your way[1].

But you can rewrite that in several ways using Guava or Java 8. These will be slightly less efficient.

Using Guava

You can use Guava's FluentIterable class. It's kind of made for your use-case.

Note that you have to create a separate Predicate, but you can reuse it at will, of course.

Predicate<String> hasLengthGreaterThanFive = new Predicate<String>() {
  @Override public boolean apply(String str) {
    return str.length() > 5;
  }
};
List<String> matchingItems = FluentIterable.from(getItems())
  .filter(hasLengthGreaterThanFive)
  .toList();

Using Java 8

Java 8 makes the previous bit of code much more readable, and you don't need to include Guava.

List<String> matchingItems = getItems().stream()
  .filter(s -> s.length() > 5)
  .collect(Collectors.toList());

1: bar some other byte-code relevant optimizations.

Upvotes: 2

Related Questions