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 doing this:
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
fruitStream.filter(
item -> !fruitStream2.anyMatch(item2 -> item2.equals(item)))
.forEach(System.out::println);
// 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?
Note
I want to use streams to learn about them. Dont want to transform them into arrays or lists
Stream.ofdoes the array creation behind the scenes, you can simply usefruitStream.filter( item -> !Stream.of("orange", "kiwi", "melon", "apple", "watermelon").anyMatch(item2 -> item2.equals(item)))…, but of course, aHashSetbased solution is more efficient.