[英]I'm told to convert a lambda with a parameterized constructor to a method reference
[英]pass parameterized constructor as method reference
是否可以将参数化构造函数作为方法引用传递给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
添加一个新的构造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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.