Stream has already been operated upon or closed - Java 8 [duplicate] - java

This question already has answers here:
Why is this java Stream operated upon twice?
(4 answers)
Closed 6 years ago.
Why I have next exception?
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)...
com.search.offer.OffersSelector.isGood(OffersSelector.java:23)
How change the code to fix it?
Stream<String> titleExclusions = ResourceUtility.contentToUtf8TreeSet("+.txt").
stream().filter(item -> item.length() == 0).collect(Collectors.toSet()).stream();
//...
titleExclusions.filter(tittle::contains).collect(Collectors.toSet()).size() == 0;//line 23

You can't operate on Streams more than once so you are better off using Collections as these can be used more than once.
Set<String> titleExclusions = ResourceUtility.contentToUtf8TreeSet("+.txt")
.stream()
.filter(item -> !item.isEmpty())
.collect(Collectors.toSet());
// uses titleExclusions
boolean noMatches = titleExclusions.stream()
.noneMatch(tittle::contains);
// uses titleExclusions again.
Note: I assume you wanted the non-blank lines from your source file instead of the sets of blank ones. filter takes a Predicate of what is retained rather than what is discarded.
Thank you #Holger for simplifying the second statement.

Related

Is it possible to create and infinite stream without limiting the size? [duplicate]

This question already has answers here:
How to create an infinite stream with Java 8
(4 answers)
How to create an infinite Stream<E> out of an Iterator<E>?
(4 answers)
Closed 1 year ago.
Can we create a Java stream with an infinite source of data (e.g. Health signals)?
Yes.
Of course, limiting the size would cause the stream to be finite.
With, for example, Stream.generate(() -> "tick") you have an infinite stream.
However, the actual implementation heavily depends on the shape of the source. If, for instance, for heart beats, I expect the stream coming from some external device, so then you'll need to setup the transmission as well.

Converting Object[] to List<Object> in this one-liner function in Java [duplicate]

This question already has answers here:
Converting Array to List
(9 answers)
Retrieving a List from a java.util.stream.Stream in Java 8
(15 answers)
Closed 3 years ago.
still very new to Java, my apologies if this has appeared before.
Basically here is the original code
public static MarketType[] convert(final String[] values) {
return ofNullable(values).map(v -> Stream.of(values))
.orElse(Stream.empty())
.map(v -> getMarketType(v))
.toArray(MarketType[]::new);
}
Since other functions changed, I really need the return type to be List<MarketType> instead of MarketType[], but is there any way that can achieve this with the minimal amount of modification for the original code?
I have been trying to put different things in the toArray function but nothing really worked.
Any help appreciated!

Java 8 bug with Stream.of()-like stream and concatenating them? [duplicate]

This question already has answers here:
Java 8 Stream IllegalStateException: Stream has already been operated on or closed
(6 answers)
Closed 4 years ago.
Why is the following java 8 code showing a bug at the second call to get()?
Stream<String> aStream = Stream.concat(Stream.of("A"), Stream.of("B"));
String a = stream.findFirst().get();
String b = stream.findFirst().get();
The "aStream" stream should see two values: "A" and "B". However, trying to read anything, after the first element has already been consumed, gives
java.lang.IllegalStateException: stream has already been operated upon or closed
Isn't it a bug in Java 8? First, why doesn't a consumed Stream.of()-created stream return an Optional with isPresent()==false? Second, why doesn't Stream.concatenate() correctly concatenate such Stream.of()-created streams?
Stream.concatenate() does concatenate the two Streams. However, once you execute a terminal operation of the combined Stream - stream.findFirst() - you can't do anything else with that Stream. You can only run one terminal operation of a Stream. That's why it's called "terminal".
If you want to obtain more than one element of the combined Stream, use a different terminal operation, such as collect:
List<String> list = stream.collect(Collectors.toList());
To clarify, the combined Stream is a single Stream<String>, not a Stream of Streams. Therefore findFirst() consumes the entire combined Stream, not just the first Stream that was uses to create the combined Stream.
Because Stream.findFirst() is a terminal operation, and terminal operations can only be run once on a given stream.

Reusing Streams in Java 8 [duplicate]

This question already has answers here:
Java 8 Stream IllegalStateException: Stream has already been operated on or closed
(6 answers)
Closed 6 years ago.
I need to calculate the ratio of two parts of the big List, wherein the first part contains the second:
Stream<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2);
int result = part1.filter(y -> y.isRight()).count() / part1.count();
But this code throws the Exception: java.lang.IllegalStateException: stream has already been operated upon or closed
Can I write a code without creating the same part1 stream in result?
You can only reuse a collection as it has memoriation of results.
List<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2).collect(toList());
double result = (double) part1.stream().filter(y -> y.isRight()).count() / part1.size();
A Stream is a builder for some code which is optimised at run time. It's execution isn't as dynamic as it appears.
Streams are not supposed to be reused, or if you want something seemed to it, you can use suppliers as mentioned here : Copy a stream to avoid "stream has already been operated upon or closed" (java 8)

Java 8 Streams Filter Intention of Lazy Evaluation [duplicate]

This question already has answers here:
Java 8 Streams: multiple filters vs. complex condition
(4 answers)
Closed 6 years ago.
Is either option 1 or option 2 below correct (e.g. one preferred over the other) or are they equivalent?
Option 1
collectionOfThings.
stream().
filter(thing -> thing.condition1() && thing.condition2())
or
Option 2
collectionOfThings
.stream()
.filter(thing -> thing.condition1())
.filter(thing -> thing.condition2())
To compile, the second one should be
collectionOfThings.
stream().
filter(thing -> thing.condition1()).
filter(thing -> thing.condition2())
They're both equivalent. Sometimes one is more readable than the other.
An alternative way of writing the second one would be to use a method reference:
collectionOfThings
.stream()
.filter(Thing::condition1)
.filter(Thing::condition2)
Also note that the convention is to place the dot at the beginning of the line rather than the end, as you would write a bulleted list.

Categories

Resources