I have a stream<A>
, where
class A {
String category();
// ...
}
I would like to get a map<String, list<A>>
, where the original stream is partitioned into sublists based on the value of category(). It is pretty trivial to have it implemented using a for loop, but is it possible to get a more elegant solution harnessing java streams?
EXAMPLE:
Given {[a, xyz], [a, zyx], [b, abc]}
, I would like to get a map:
a -> {[a, xyz], [a, zyx]}
b -> {[b, abc]}
A stream should be operated on (invoking an intermediate or terminal stream operation) only once. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. So the answer is no, streams are not meant to be reused.
So the simple answer is : NO, we cannot reuse the streams or traverse the streams multiple times. Any attempt to do so will result in error : Stream has already been operated on or closed.
Note that there are built-in infinite streams such as java. util. Random. ints() which gives you an infinite stream of random integers.
No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.
Use the groupingBy collector.
stream.collect(Collectors.groupingBy(A::category));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With