简体   繁体   中英

Converting from list of one POJO to another

I have a list of POJOs in Java that I need to convert to a list of POJOs of another type. Both POJOs have two String fields. Is there a better way of doing this than just iterating through the original list and adding new items to a resultant list? I know that in Java 8 I can write a Function which implements the apply method but I am using Java 7. Is there a more efficient way of doing this in Java 7? Example code below

final List<Tracking> list = new ArrayList<>();

for (DJTracking djTracking : trackingInformation) {
    list.add(new Tracking(djTracking.getTrackingNumber(), djTracking.getTrackingUrl()));
}

return list;

One simple way is to break that code you mentioned, I mean write a method in firstClass for converting it to the second one, this may does not improve the performance but is cleaner.

public Tracking convertToTracking(){
       return new Tracking(this.getTrackingNumber(), this.getTrackingUrl());
}

and in anywhere you want you can convert the list simply:

final List<Tracking> list = new ArrayList<>();

for (DJTracking djTracking : trackingInformation) {
    list.add(djTracking.convertToTracking());
}

return list;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM