Sean Patrick Floyd Sean Patrick Floyd - 25 days ago 18
Java Question

Guava: how to combine filter and transform?

I have a collection of Strings, and I would like to convert it to a collection of strings were all empty or null Strings are removed and all others are trimmed.

I can do it in two steps:

final List<String> tokens =
Lists.newArrayList(" some ", null, "stuff\t", "", " \nhere");
final Collection<String> filtered =
Collections2.filter(
Collections2.transform(tokens, new Function<String, String>(){

// This is a substitute for StringUtils.stripToEmpty()
// why doesn't Guava have stuff like that?
@Override
public String apply(final String input){
return input == null ? "" : input.trim();
}
}), new Predicate<String>(){

@Override
public boolean apply(final String input){
return !Strings.isNullOrEmpty(input);
}

});
System.out.println(filtered);
// Output, as desired: [some, stuff, here]


But is there a Guava way of combining the two actions into one step?

Answer

In the upcoming latest version(12.0) of Guava, there will be a class named FluentIterable. This class provides the missing fluent API for this kind of stuff.

Using FluentIterable, you should be able doing something like this:

final Collection<String> filtered = FluentIterable
    .from(tokens)
    .transform(new Function<String, String>() {
       @Override
       public String apply(final String input) {
         return input == null ? "" : input.trim();
       }
     })
    .filter(new Predicate<String>() {
       @Override
       public boolean apply(final String input) {
         return !Strings.isNullOrEmpty(input);
       }
     })
   .toImmutableList();
Comments