How to pass argument to class constructor when initialzed thru ::new in Java8

Viewed 6614

I am using java 8 stream API to perform action on a list of Store objects.

Store takes a String argument and a Mapper object. Mapper will be same for all Store object.

Question: How can I pass Mapper object when I initialize Store here .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());
    }
}
3 Answers

Using Stream generator

Stream.generate(Item::new)
                .map(item -> new Item("Hello", "Hi"))
                .limit(10)
                .forEach(System.out::println);

Related