Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 functional way of getting consecutive numbers of a list

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

like image 252
ttt Avatar asked Dec 24 '22 03:12

ttt


1 Answers

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());
like image 125
Naman Avatar answered Dec 26 '22 00:12

Naman