简体   繁体   English

从一个POJO的列表转换为另一个

[英]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. 我有一个Java中的POJO列表,我需要将其转换为其他类型的POJO列表。 Both POJOs have two String fields. 两个POJO都有两个String字段。 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? 我知道在Java 8中我可以编写一个实现apply方法的函数,但是我正在使用Java7。在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. 一种简单的方法是破坏您提到的代码,我的意思是在firstClass中编写一个方法将其转换为第二个方法,这可能不会提高性能,但更干净。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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