Guava: how to combine filter and transform?

前端 未结 1 1822
死守一世寂寞
死守一世寂寞 2021-01-30 10:36

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

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 11:09

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

    0 讨论(0)
提交回复
热议问题