I am not able to understand how the function gets passed via a lambda into this method
public class OrderUtil {
public static <I, O> List<O> runInBatches(List<I> inputList,
Function<List<I>, List<O>> functionToRunInBatches) {
return Lists.partition(inputList, BATCH_CHUNK_SIZE).stream()
.flatMap(batch -> functionToRunInBatches.apply(batch).stream())
.collect(toList());
}
}
I see the below code, I am not able to understand how the lambda function below translates to functionToRunInBatches above? orderDao.getOrderForDates(...) takes three parameters (orders, startdate, enddate) but my function takes a list and returns a list. How does this call work fine?
I have read the tutorials and documentation on Function.
Would it be possible for someone to break down how the lambda gets mapped to the Function above? I am unable to visualise how this ends up working.
private List<Order> getOrderForDates(List<Long> orderNumbers,
tring startDate, String endDate){
return OrderUtil.runInBatches(orderNumbers,
orderBatch -> orderDAO.getOrderForDates(orderBatch, startDate, endDate));
}
The lambda is turned into a new Function
object by the compiler. It overrides the apply
method with the code given in the lambda expression.
So this:
private List<Order> getOrderForDates(List<Long> orderNumbers, String startDate, String endDate){
return OrderUtil.runInBatches(orderNumbers, orderBatch -> orderDAO.getOrderForDates(orderBatch, startDate, endDate));
}
is equivalent to this:
private List<Order> getOrderForDates(List<Long> orderNumbers, String startDate, String endDate){
return OrderUtil.runInBatches(orderNumbers, new Function<List<Long>, List<Order>>() {
@Override
public List<Order> apply(List<Long> orderBatch) {
return orderDAO.getOrderForDates(orderBatch, startDate, endDate);
}
});
}
Your runInBatches
method then simply calls apply
on that Function
object.