Java 8 Stream closes when using a card inside a card

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 
+4
source share
1 answer

The problem is that your code tries to process the second Stream twice (once for each element of the first Stream ). A Stream can only be processed once, just as an Iterator can only Iterator over elements of a base class.

If your first Stream had only one element, the code would work, since the second Stream processed only once.

In the code that works, you create a new Stream (from secondList ) for each element of the first Stream , so each Stream processed once, regardless of how many elements are in the Stream first.

+5
source

All Articles