0

I have a concrete class MyObjectWrapper and an Interface MyObject.

MyObjectWrapper implements MyObject

MyObjectWrapper.jsonObject holds an instance of MyObjectJson.

The constructor signature for MyObjectWrapper is:

MyObjectWrapper(MyObjectJson myObjectJson, ServiceManager serviceManager)

I want to provide an instance of PaginatedList to a method and include a reference to the above MyObjectWrapper constructor so it can be referenced for each item in PaginatedList such that the result of my stream() is a new instance of PaginatedList where MyObjectWrapper is the concrete MyObject.

I will have reference to this.getServiceManager() from wherever mapList is called. I am assuming I will have to pass the Constructor for MyObjectWrapper as a Function but am unsure how to write the method signature nor how to properly reference the Constructor as a map function within the method itself.

My code works as written below but I want to make the method generic so I do not have to duplicate it for every type.

PaginatedList<T> extends ArrayList<T>
    private PaginatedList<MyObject> mapList(PaginatedList<MyObjectJson> paginatedList) {
        return paginatedList.stream()
                .map(jsonObject -> new MyObjectWrapper(jsonObject, this.getServiceManager()))
                .collect(Collectors.toCollection(PaginatedList::new));
    }
I. Jones
  • 3
  • 1
  • 2
    You already have an example in your code: `MyObjectWrapper::new`. If you are needing to pre-configure only certain parameters, you can say `moj -> new MyObjectWrapper(moj, serviceManagerVariable)`. – chrylis -cautiouslyoptimistic- Aug 13 '21 at 17:12

1 Answers1

0

Since the constructor takes both a MyObjectJson and a ServiceManager as input, you don't need a Function as input but a BiFunction<? super MyObjectJson, ? super ServiceManager, ? extends MyObject>1:

private PaginatedList<MyObject> mapList(PaginatedList<MyObjectJson> paginatedList,
      BiFunction<? super MyObjectJson, ? super ServiceManager, ? extends MyObject> myObjectProducer) {
    return paginatedList.stream()
            .map(jsonObject -> myObjectProducer.apply(jsonObject, this.getServiceManager()))
            .collect(Collectors.toCollection(PaginatedList::new));
}

and just call it with mapList(someList, MyObjectWrapper::new).

1 for why the super/extends, read What is PECS

Didier L
  • 18,905
  • 10
  • 61
  • 103