I would like to flatten arbitrary deeply nested collections/structures of elements of some type T in Java, optimally with
Is there a java library which can handle this?
Guava seems to only handle one nesting level, i.e. Collection<Collection<T>>
--flatten--> Collection<T>
.
lambdaj looks promising: can I somehow combine on()
, asIterator()
and flattenIterator()
to achieve this? In a statically type-safe manner?
Stream flatMap() method is used to flatten a Stream of collections to a stream of objects. The objects are combined from all the collections in the original stream. The flatMap() method is a one-to-many transformation to the elements of the stream and then flattening the resulting elements into a new stream.
flatMap() method. The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.
Guava will probably support this eventually :
http://code.google.com/p/guava-libraries/issues/detail?id=174
(It might be easiest to read that from the bottom up, since the thinking on it has shifted a few times over its lifetime.)
Not based on either of the above, but perhaps a DeepIterator class that is constructed with a Collection whose next() method looks at the next Object and if it is a instanceof Collection then pushes the current iterator on Stack and recurses into that Collection's iterator.
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