Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partition java streams in categories [duplicate]

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]}
like image 474
Grzenio Avatar asked Apr 25 '17 11:04

Grzenio


People also ask

Can we reuse streams in Java?

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.

Can Java stream be reused and visited many times?

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.

Can Java streams be of infinite size?

Note that there are built-in infinite streams such as java. util. Random. ints() which gives you an infinite stream of random integers.

Does Java streams have limited storage?

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.


1 Answers

Use the groupingBy collector.

stream.collect(Collectors.groupingBy(A::category));

like image 77
Jure Kolenko Avatar answered Oct 05 '22 13:10

Jure Kolenko