Di Zou Di Zou - 7 months ago 8
Java Question

How do I take an Iterable of one class and turn it into an Iterable of another class?

I have an iterable of one class:

Iterable<ClassA> classAIterable
. I have a second class like this:

public class ClassB {
private final ClassA classA;
public ClassB(ClassA a) {
this.classA = a;
}
}


I would like to take every
ClassA
object in
classAIterable
and turn it into a
ClassB
object that contains a
ClassA
object and put them into an iterable of
ClassB
.

How would I do this? Thanks!

Answer

You can convert your Iterable to a Stream by accessing the Spliterator, by using StreamSupport.stream. In the Stream you can map the elements from ClassA to ClassB, then collect them into a List, which is Iterable.

Iterable<ClassB> iterB = StreamSupport.stream(iterable.spliterator(), false)
    .map(ClassB::new)
    .collect(Collectors.toList());