java中 两个不同类对象list,属性一样,如何copy
如果您有两个不同的类,但它们拥有相同的属性,并且您想要从一个类的列表复制到另一个类的列表,您可以使用以下方法:
-
使用循环:
您可以遍历原始列表,并为每个元素创建目标类的新实例。 -
使用
Stream
API:
如果您使用的是 Java 8 或更高版本,您可以利用Stream
API 来简化这个过程。
下面是一个具体的例子,假设您有两个类 SourceItem
和 TargetItem
,它们都有相同的属性 name
和 value
。
示例代码
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;// 原始类
class SourceItem {private String name;private int value;public SourceItem(String name, int value) {this.name = name;this.value = value;}public String getName() {return name;}public int getValue() {return value;}
}// 目标类
class TargetItem {private String name;private int value;public TargetItem(String name, int value) {this.name = name;this.value = value;}public String getName() {return name;}public int getValue() {return value;}
}public class ListCopyExample {public static void main(String[] args) {List<SourceItem> sourceList = new ArrayList<>();sourceList.add(new SourceItem("Item 1", 100));sourceList.add(new SourceItem("Item 2", 200));// 使用 Stream API 复制列表List<TargetItem> targetList = sourceList.stream().map(source -> new TargetItem(source.getName(), source.getValue())).collect(Collectors.toList());System.out.println("Original List: " + sourceList);System.out.println("Copied List: " + targetList);}
}
在这个例子中,我们使用了 Stream
API 的 map
方法来转换每个 SourceItem
成为 TargetItem
。如果您更喜欢使用传统的循环方式,可以使用以下代码:
import java.util.ArrayList;
import java.util.List;class SourceItem {private String name;private int value;public SourceItem(String name, int value) {this.name = name;this.value = value;}public String getName() {return name;}public int getValue() {return value;}
}class TargetItem {private String name;private int value;public TargetItem(String name, int value) {this.name = name;this.value = value;}public String getName() {return name;}public int getValue() {return value;}
}public class ListCopyExample {public static void main(String[] args) {List<SourceItem> sourceList = new ArrayList<>();sourceList.add(new SourceItem("Item 1", 100));sourceList.add(new SourceItem("Item 2", 200));// 使用循环复制列表List<TargetItem> targetList = new ArrayList<>();for (SourceItem sourceItem : sourceList) {TargetItem targetItem = new TargetItem(sourceItem.getName(), sourceItem.getValue());targetList.add(targetItem);}System.out.println("Original List: " + sourceList);System.out.println("Copied List: " + targetList);}
}
这两种方法都可以有效地完成任务。使用哪种方法取决于您的个人偏好以及项目的需求。