Mayday Mayday - 1 month ago 6x
Java Question

Operations between java Streams

I am trying to find the fastest way, and less complex way to do some union/exclude/intersection operations over Java SE 8 Streams.

I am following Stack Overflow documentation in the following way:

Stream<String> fruitStream = Stream.of("apple", "banana", "pear", "kiwi", "orange");
Stream<String> fruitStream2 = Stream.of("orange", "kiwi", "melon", "apple", "watermelon");

//Trying to create exclude operation
item -> !fruitStream2.anyMatch(item2 -> item2.equals(item)))
// Expected result: fruitStream - fruitStream2: ["banana","pear"]

I get the following Exception:

java.lang.IllegalStateException: stream has already been operated upon or closed

If I was able to do this operation, I could develope myself all the rest, union, intersection etc...

So, the 2 points are:

1) What am I doing wrong in this solution to get that Exception?

2) Is there a less complex way to perform operations between 2 streams?


I want to use streams to learn about them. Dont want to transform them into arrays or lists


The first time item -> !fruitStream2.anyMatch(item2 -> item2.equals(item)) executes, it consumes fruitStream2. fruitStream2 can not be used again to filter the second item in fruitStream1.

Rather than using a second stream, why not create a Set and use contains?

Set<String> otherFruits = new HashSet<>(); // Add the fruits.
fruitStream.filter(f -> !otherFruits.contains(f)).forEach(System.out::println);