I am trying to combine two streams. I ran into a problem that my thread is shutting down and I don't understand why. Could someone explain to me why the following happens.
The code below does not work. I get an exception in the flatMap function that the stream is already closed.
private Stream<KeyValuePair<T, U>> joinStreams(Stream<T> first, Stream<U> second) { return first .map(x -> second .map(y -> new KeyValuePair<T, U>(x, y)) ) .flatMap(x -> x); }
When I first compile a list from a second thread and then grab a stream from that list, it works. See the example below.
private Stream<KeyValuePair<T, U>> joinStreams(Stream<T> first, Stream<U> second) { List<U> secondList = second.collect(Collectors.toList()); return first .map(x -> secondList.stream() .map(y -> new KeyValuePair<T, U>(x, y)) ) .flatMap(x -> x); }
I canβt understand why this is happening. Can anyone explain this?
Edit:
Sample code calling this function.
List<Integer> numbers1 = Arrays.asList(1, 2); List<Integer> numbers2 = Arrays.asList(3, 4); List<KeyValuePair<Integer, Integer>> combined = joinStreams(numbers1.stream(), numbers2.stream()) .collect(Collectors.toList()); // Expected result // 1 3 // 1 4 // 2 3 // 2 4
source share