gpt4 book ai didi

java - 将参数化构造函数作为方法引用传递

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:38 25 4
gpt4 key购买 nike

是否可以将参数化构造函数作为方法引用传递给 map

我的代码中有一个看起来像这样的工具

items.stream()
.map(it -> new LightItem(item.getId(), item.getName())
.collect(Collectors.toList());

我的 items 列表包含几个 Item 对象

Item
id, name, reference, key...

LightItem 只有两个字段

LightItem
id, name

要是能这样就好了

items.stream().map(LightItem::new).collect(Collectors.toList())

最佳答案

这里只有一种方法可以使用构造函数,你必须在LightItem 类中添加一个新的构造函数:

public LightItem(Item item) {
this.id = item.getId();
this.name = item.getName();
}

这将允许您使用您编写的代码:

items.stream().map(LightItem::new).collect(Collectors.toList())

如果你真的不想给 LightItem 添加一个新的构造函数,有一个办法:

class MyClass {

public List<LightItem> someMethod() {
return items.stream()
.map(MyClass::buildLightItem)
.collect(Collectors.toList());
}

private static LightItem buildLightItem(Item item) {
return new LightItem(item.getId(), item.getName());
}

}

关于java - 将参数化构造函数作为方法引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com