Java8 subscriptions from list <> using lambdas

I have a problem that, in my opinion, would be ideal for threads and / or lambda. On the other hand, I do not want to re-complement this, but since he will use this particular technique in many ways (the launch function in the sublist), I would like some ideas on how to get this right from the very beginning.

I have a List<Product> productList .

I want to be able to productList over all signatures in a productList . For example, all sublists with size = 30. This sublist should then be used as an argument to the function.

This is my current, naive solution:

 List<Product> products=... // This example uses sublists of size 30 for (int i = 0; i < products.size() - 29; i++) { // sublist start index is inclusive, but end index is exclusive List<Product> sublist = products.subList(i, i + 30); Double res = calc(sublist); } // an example of a function would be moving average 

How will this be implemented using lambdas?

EDIT I ​​tried to come up with the simplest possible example to illustrate the problem. After some comments, I realized that the ideal example is moving average calculation. The first MAVG is calculated on the sublist [0..29], the second on [1..30], the third on [2.31], etc.

+7
source share
3 answers

If I miss something obvious ...

 IntStream.range(0, products.size() - 29) .mapToObj(i -> products.subList(i, i + 30)) .map(list -> calc(list)) .forEach... // or any other terminal op 

Well, if you want to run more than one function for these subscriptions, for example:

 double result = calc(sublist) log(sublist) // void double res = diffCalc(sublist) 

you probably are not left with the usual loop.

Operation

a map does one thing in the sublist, it can be made to do more in the stream, but it will look really ugly IMO.

+6
source

If you don't mind using third-party libraries, there is a subLists method in StreamEx that does exactly what you want:

 List<Product> products = ... Stream<List<Product>> lists = StreamEx.ofSubLists(products, 30, 1); 
+4
source

I think the code may be less clear when using lambdas. Maybe plain old if better than modern lambda ?

  int sizeSubList = 30; for (int i = 0; i < products.size(); i++) calc(products.subList(i, Math.min(i + sizeSubList, products.size()))); 
+1
source

All Articles