java 8ストリームAPIを使用してStore
オブジェクトのリストに対してアクションを実行しています。Java8でinitialised thru :: newを実行したときに、クラスコンストラクタに引数を渡す方法
Store
は、String
引数とMapper
オブジェクトをとります。 Mapper
はすべてのStore
オブジェクトで同じになります。
質問:初期化時にMapper
オブジェクトを渡すには、Store
ここに.map(Store::new)
?
public class Store {
public Store(String name, Mapper mapper) {
}
}
public class Mapper {
}
public class Test {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
Mapper mapper = new Mapper();
// compile time problem at Store::new because it takes 2 arguments
List<Store> actions =
names.stream()
.map(Store::new)
.collect(Collectors.toList());
}
}
以下が便利な場合があります。https://stackoverflow.com/questions/25468711/method-references-with-a-parameter また、静的メソッド参照の代わりにラムダ式を使用する方法もあります。 – thepieterdc