番石榴:如何结合过滤和转换? [英] Guava: how to combine filter and transform?

查看:144
本文介绍了番石榴:如何结合过滤和转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串的集合,我想将它转换为字符串的集合,所有字符串都是空的或删除字符串被删除,所有其他字符串被修剪。

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.

我可以分两步完成:

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?

推荐答案

即将推出的最新版本中( 12.0)Guava,会有一个名为 FluentIterable
这个类为这类东西提供了缺少的流畅API。

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.

使用FluentIterable,你应该可以这样做:

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

这篇关于番石榴:如何结合过滤和转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆