簡體   English   中英

傳遞參數化構造函數作為方法引用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM