I would like to flatten arbitrary deeply nested collections/structures of elements of some type T in Java, optimally with
- only having a live view and not a copied collection;
- not only handling Collections, but also Iterator, arrays of T of arbitrary dimension, Iterable, and all these structures arbitrarily mixed and nested;
- statical type-safety.
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?
DeepIterator
class that is constructed with aCollection
whosenext()
method looks at the nextObject
and if it is ainstanceof Collection
then pushes the currentiterator
onStack
and recurses into thatCollection
's iterator. – GassawayObject
s. Am I missing something? – GassawayDeepIterator
aproach sounds promising, but I don't think you can achieve general and statical type-safety solution. I don't see how you can even express such entity in Java. – ContortionistCollection<T extends Interface1?
what would happen if some nested element is not a kind ofInterface1
? Omit those elements? Throw exception? – Gassaway