简体   繁体   English

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

[英]pass parameterized constructor as method reference

Is it possible to pass parameterized constructor as method reference to map ? 是否可以将参数化构造函数作为方法引用传递给map

I've got a facility in my code that looks like this 我的代码中有一个看起来像这样的工具

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

My items list constains several Item objects 我的items列表包含几个Item对象

Item
   id, name, reference, key...

whereas LightItem has only two fields LightItem只有两个字段

LightItem
    id, name

It would be good if it was possible to do something like this 如果有可能做这样的事情会很好

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

There's only one way to use constructor here, you have to add a new constructor to LightItem class: 这里只有一种方法可以使用构造函数,你必须在LightItem类中添加一个新的构造函数:

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

This will allow you to use the code you wrote: 这将允许您使用您编写的代码:

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

If you really don't want to add a new constructor to LightItem , there's way around: 如果你真的不想为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM