Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Convert a collection of classA to collection of classB

Given a List of Foo myFoos, I need to map those to a collection of a different class, say Bar. I do it like this now:

List<Bar> myBars = new...
for(Foo f : foos) {
    Bar b = new Bar();
    b.setAProperty(f.getProperty);
    b.setAnotherProp(f.getAnotherProp);
    myBars.add(b);
}

So, is there an easier way to do this? Granted this is pretty easy, but I'm wondering if there's any magic out there that would morph the foos to bars without having to manually walk the list, particularly because my input list can be big.
If not, do you guys know if the compiler does anything to optimize this? I'm worried mainly about performance.

Thanks!

--
Llappall

like image 240
llappall Avatar asked Feb 01 '26 12:02

llappall


1 Answers

You can't really avoid walking the list, because you have to convert every item!

But you can simplify your syntax if you write a Bar constructor that takes a Foo. Then your loop can become:

for(foo f : foos) {
    myBars.add(new Bar(f));
}

Depending on your scenario, an alternative is to not create the list of Bars at all. Instead, you can simply add a Foo.getAsBar() method, so that you dynamically generate a Bar object as required. If the number of elements in the container is higher than the total number of times that you'll need to access them, then this may be more efficient.

like image 184
Oliver Charlesworth Avatar answered Feb 03 '26 01:02

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!