如何在条件下使用java8 stream filter()方法?

时间:2018-03-28 02:04:39

标签: java java-8 java-stream

我想知道如何在条件下选择使用流过滤器。也就是说,我是否可以使用fiter来决定变量。

我原来的代码是:

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

那么我可以将两个return语句混合成一个吗?喜欢

return list.parallelStream()
            .filterIfKeywordNonNull(dto -> dto.getString().contains(keyword))
            .map(...)
            .collect(Collectors.toList());

提前谢谢。

3 个答案:

答案 0 :(得分:3)

您只需将keyword测试添加到过滤器即可。像,

return list.parallelStream()
        .filter(dto -> keyword == null || dto.getString().contains(keyword))
        .map(...)
        .collect(Collectors.toList());

为了提高效率,还可以构建Stream一次,并使用三元组保存临时变量。像,

Stream<T> stream = (keyword == null) ? list.parallelStream() :
    list.parallelStream().filter(dto -> dto.getString().contains(keyword));
return stream.map(...).collect(Collectors.toList());

您可以在回复中使用三元组,但是您必须重复mapcollect来电。

答案 1 :(得分:1)

.filter(getFilter(dto));

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`)
}

答案 2 :(得分:0)

因为过滤器不是结束流条件。你可以随时添加它。那么,这个怎么样?

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