[英]Guava: how to combine filter and transform?
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. 我有一个字符串的集合,我想将它转换为字符串集合全部为空或null删除字符串,其他所有字符串都被修剪。
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? 但有没有一种将这两种行为合并为一步的番石榴方式?
In the upcoming latest version(12.0) of Guava, there will be a class named FluentIterable . 在
即将推出的Guava最新版本(12.0)中,将有一个名为FluentIterable的类。 This class provides the missing fluent API for this kind of stuff. 这个类为这类东西提供了缺少的流畅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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.