2010-11-25 32 views
46

我有一个字符串的集合,我想将它转换为一个字符串集合都是空的或空的字符串被删除,所有其他都被修剪。番石榴:如何结合过滤和变换?

我可以做的两个步骤:

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] 

但有两个动作组合成一个步骤的番石榴方式?

+0

为skaffman指出,这是对最简单的办法做到这一点;至于你关于一些非常用的函数没有被烘焙的提示 - 为什么不要求`Strings` api为这样的明智例子添加一些静态的`Function`和`Predicate`?我在http://code.google.com/p/guava-libraries/issues/list上找到了维护人员的合理响应。 – Carl 2010-11-25 17:06:33

+0

@Carl以及我已经在管道中发布了http://code.google.com/p/guava-libraries/issues/list?can=2&q=reporter:sean,mostlymagic.com,我不想要让他们紧张起来。但是我可能会这样做,因为最终我希望Guava能够替代commons/lang和commons/io,而且为此我们还有很长的路要走。 – 2010-11-25 17:17:43

回答

77

即将推出最新版本(12.0)的番石榴,将有一个类FluentIterable。 该类为这类东西提供了缺少的流畅API。

使用FluentIterable,你应该能够做这样的事情:

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