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!
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());
Of course it might not be suitable in your case, but as a variant of solution:
1) U can create interface:
interface interfaceC {
}
2) And implement it in both ClassA
and ClassB
:
class ClassA implements interfaceC {
}
class ClassB implements interfaceC {
}
3) And then use iterable of interfaceC
class classIterable implements Iterable<interfaceC> {
private List<interfaceC> internalList = null;
}
Might work for u
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.