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)
Related
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.
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.
This question already has answers here:
Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
(14 answers)
Is there an accepted Java equivalent to Python's zip()? [duplicate]
(1 answer)
Closed 5 years ago.
Say I have two streams:
Stream<String> ids = Stream.of("id1","id2","id3","id4","id5");
Stream<MyObj> objects = Stream.of(new MyObj(null, "some data"), new MyObj(null, "some other data");
Now I would like to update my objects stream with the data from ids. The result whould be equivalent to the following Stream:
Stream<MyObj> objects = Stream.of(new MyObj("id1", "some data"), new MyObj("id2", "some other data");
I thus wonder if there is a way to consume both streams, one element at the time. I imagine some kind of "DoubleConsumer" (nothing to do with double) of the sort:
Stream<MyObj> result = DoubleConsumer.of(ids, objects)
.map((id, myobj) -> combine(id, myobj));
MyObj combine(String id, MyObj myobj) {
myobj.set(id);
return myobj;
}
Any idea how to achieve something like this?
Update
I know that I can solve this in the case of list with some double loop, or with FuncionalJava's zipfunction. However the question is how to do this with Java Streams.
Do you want Stream.map. eg.
Stream<MyObj> objs = ids.map(id->new MyObj(id, "some data"));
This does exactly what op wants. Then if they want to update the values of the objects they can afterwards, and the objects know their id so that can be gotten.
If they want to "zip" two streams, they should check the existing answers.
This question already has answers here:
How to add two arrays in Java in parallel manner?
(5 answers)
Closed 6 years ago.
I already found this question here, but it be great to see more options.
How to add two arrays in Java in parallel manner?
I have 2 float/ double arrays (around 10.000 to 100.000 entries) where I need to perform component wise operations on (e.g. division, multiplication, addition).
I'm working on a PC with 4 to 32 CPUs, thus I'd love to use this power and execute these computations in parallel in a Java environment.
What are good ways to do that in Java?
Thank you for your answers in advance!
Something like this?
double [] t0 = {....};
double [] t1 = {....};
double [] result =new double[t0.length];
IntStream.range(0, t0.length).parallel().forEach(i -> result[i] = t0[i] + t1[i]);
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.