简体   繁体   中英

pass parameterized constructor as method reference

Is it possible to pass parameterized constructor as method reference to 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

Item
   id, name, reference, key...

whereas LightItem has only two fields

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:

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:

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());
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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