Java Guava:如何结合过滤和变换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4277734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:16:52  来源:igfitidea点击:

Guava: how to combine filter and transform?

javaguava

提问by Sean Patrick Floyd

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?

但是有没有一种 Guava 方法可以将这两个动作合并为一个步骤?

采纳答案by Olivier Heidemann

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

即将发布的 Guava 最新版本(12.0)中,将有一个名为FluentIterable的类。此类为此类内容提供了缺少的流畅 API。

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

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