For example I have a list of integers, as List(1,2,3,4,5,6,7)
I want to get all of the combinations of consectuive 3 numbers in Java 8 more functional way to learn Java 8. (I know how to do it in a imperative way)
So the result for above can be a list of list as:
List(List(1,2,3), List(2,3,4), List(3,4,5), List(4,5,6), List(5,6,7))
Thanks
You can do it using List.subList
while iterating over it:
final int subListSize = 3;
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> sublists = IntStream.rangeClosed(0, list.size() - subListSize)
.mapToObj(i -> list.subList(i, i + subListSize))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With