Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava: how to combine filter and transform?

Tags:

java

guava

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?

like image 368
Sean Patrick Floyd Avatar asked Nov 25 '10 13:11

Sean Patrick Floyd


Video Answer


1 Answers

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(); 
like image 164
Olivier Heidemann Avatar answered Sep 30 '22 19:09

Olivier Heidemann