如何从两个不同的列表对象复制列表项

huangapple go评论59阅读模式
英文:

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&lt;TemplateObject&gt; list1;
List&lt;InUseObject&gt; 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&lt;InUseObject&gt; list2 = list1.stream()
        .map(obj -&gt; 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&lt;InUseObject&gt; 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&lt;InUseObject&gt; out = in.stream()
                          .map(InUseObject::new)
                          .collect(Collectors::toList);

Of course your InUseObject has to copy every common field from TemplateObject in its constructor.

huangapple
  • 本文由 发表于 2020年7月27日 23:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63118851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定