Di Zou Di Zou - 2 years ago 67
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
object in
and turn it into a
object that contains a
object and put them into an iterable of

How would I do this? Thanks!

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download