Stream pipelines Using streams many times

Sometimes after mapping and filtering a stream, you need to use it more than one time. For example, find the maximum and count all the elements of a resulted sequence. But it is impossible to do using standard stream API.

In this practice, you need to implement a method that solves this problem. The method should save the stream and create a supplier, that can return this stream over and over again.

You can look at the hints and useful links if you aren't sure how to solve the problem.

For example, this code should output 4, 8, 2 on separate lines:

Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8});
Supplier<Stream<Integer>> saved = saveStream(stream.filter(e -> e % 2 == 0));

System.out.println(saved.get().count());
System.out.println(saved.get().max(Integer::compareTo).get());
System.out.println(saved.get().min(Integer::compareTo).get());

Report a typo

Sample Input 1:

1 2 3 4 5 6 7 8

Sample Output 1:

4
8
2
import java.util.function.*;
import java.util.stream.*;

import static java.util.stream.Collectors.*;

class FunctionUtils {

    public static <T> Supplier<Stream<T>> saveStream(Stream<T> stream) {
        return stream.collect(toList())::stream;
    }

}


import java.util.function.*;
import java.util.stream.*;

class FunctionUtils {
    
    public static <T> Supplier<Stream<T>> saveStream(Stream<T> stream) {
        // write your code here
        List<T> data = stream.collect(Collectors.toList());
        
        return () -> data.stream();
    }

}
posted @ 2020-09-30 08:34  longlong6296  阅读(63)  评论(0)    收藏  举报