[英]How to use java8 stream filter() method under condition?
I wonder how to choose to use stream filter under condition. 我想知道如何选择在条件下使用流过滤器。 That is, whether I can use fiter or not decided by a variable. 就是说,我是否可以使用更合适的变量。
My original codes are: 我的原始代码是:
if (keyword == null) {
return list.parallelStream()
//not using filter
.map(...)
.collect(Collectors.toList());
}
return list.parallelStream()
.filter(dto -> dto.getString().contains(keyword))
.map(...)
.collect(Collectors.toList());
So can I mix the two return statements into one? 那么我可以将两个return语句混合成一个吗? Like 喜欢
return list.parallelStream()
.filterIfKeywordNonNull(dto -> dto.getString().contains(keyword))
.map(...)
.collect(Collectors.toList());
Thank you in advance. 先感谢您。
You could simply add the keyword
test to your filter. 您可以简单地将keyword
test添加到过滤器中。 Like, 喜欢,
return list.parallelStream()
.filter(dto -> keyword == null || dto.getString().contains(keyword))
.map(...)
.collect(Collectors.toList());
For improved efficiency, it's also possible to build the Stream
once and save it a temporary variable using a ternary. 为了提高效率,还可以只构建一次Stream
并使用三进制将其保存为临时变量。 Like, 喜欢,
Stream<T> stream = (keyword == null) ? list.parallelStream() :
list.parallelStream().filter(dto -> dto.getString().contains(keyword));
return stream.map(...).collect(Collectors.toList());
You could use the ternary in the return, but then you have to repeat the map
and collect
calls. 您可以在返回中使用三元数,但随后必须重复map
并collect
调用。
.filter(getFilter(dto));
and 和
private static Predicate getFilter(String dto){
// logic here. either return Filter A's singleton instance or return Null filter (that allows to pass everything i.e. `(dto)-> true`)
}
since filter is not a ending stream condition. 因为filter不是结束流条件。 you could add it at anytime. 您可以随时添加。 so, how about this? 那么,这呢?
public class ConditionalStreams {
//send your stream, a boolean, and the filter condition
public static Stream<Integer> filterFun(Stream<Integer> stream, boolean needToFilter, Predicate<Integer> filterStream){
if(needToFilter)
return stream.filter(filterStream);
else
return stream;
}
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6);
// create your filter condition
Predicate<Integer> filterStream = (num)->num%2==0;
System.out.println("without filter: ");
//call the function, pass parameters and return the right stream and process it.
filterFun(numbers.parallelStream(),false,filterStream)
.forEach(System.out::println);
System.out.println("with filter : ");
filterFun(numbers.parallelStream(),true,filterStream)
.forEach(System.out::println);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.