英文:
How to copy List items from two different List objects
问题
我有两个如下的列表:
List<TemplateObject> list1;
List<InUseObject> list2;
我需要从模板(源)中读取,并通过从模板复制所有元素值来创建新的InUse(目标)实例。假设两个列表中的所有字段/元素具有相同的数据类型。
有多种方法可以实现它(例如克隆、浅复制/深复制)。
问题:如何使用Java 8+来实现它?最好是一行代码。
英文:
I have two lists like below:
List<TemplateObject> list1;
List<InUseObject> list2;
I need to read from Template (source) and create new Instance of InUse (target) by getting all element values copied from Template. Given all the fields/elements have same data type in both the lists.
There are multiple ways of achieving it (say clone, shallow/deep copying).
Question: How do I achieve it using Java 8+. Preferably one liner may be?
答案1
得分: 3
你可以像这样使用 Stream#map
:
List<InUseObject> list2 = list1.stream()
.map(obj -> new InUseObject(obj.getId(), obj.getPropertyname(), obj.getPropertyvalue()))
.collect(Collectors.toList());
你也可以在 InUseObject
中定义一个接受 TemplateObject
的构造函数:
public InUseObject(final TemplateObject obj) {
this(obj.getId(), obj.getPropertyname(), obj.getPropertyvalue());
}
然后在映射时使用构造函数引用:
List<InUseObject> list2 = list1.stream()
.map(InUseObject::new)
.collect(Collectors.toList());
英文:
You can use Stream#map
like so:
List<InUseObject> list2 = list1.stream()
.map(obj -> new InUseObject(obj.getId(), obj.getPropertyname(), obj.getPropertyvalue()))
.collect(Collectors.toList());
You can also define a constructor in InUseObject
accepting a TemplateObject
:
public InUseObject(final TemplateObject obj) {
this(obj.getId(), obj.getPropertyname(), obj.getPropertyvalue());
}
You can then use a constructor reference when mapping.
List<InUseObject> list2 = list1.stream()
.map(InUseObject::new)
.collect(Collectors.toList());
答案2
得分: 1
List<InUseObject> out = in.stream()
.map(InUseObject::new)
.collect(Collectors::toList);
当然,你的InUseObject在其构造函数中必须从TemplateObject复制每个公共字段。
英文:
List<InUseObject> out = in.stream()
.map(InUseObject::new)
.collect(Collectors::toList);
Of course your InUseObject has to copy every common field from TemplateObject in its constructor.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论