Reputation: 4004
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
Upvotes: 4
Views: 1955
Reputation: 4496
You can also do it using the jOOλ library and its Seq.sliding()
method (Seq
is a sequential Stream
):
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> sublists = Seq.seq(list)
.sliding(3)
.map(Collectable::toList)
.toList();
which yields:
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
Note that:
ArrayList
s are created)List<List<T>> sublists(List<T> list, int sublistSize)
list
while nullpointer's is a list of views of original list
list
nor created sublists
are modified afterwards so it doesn't matter (and it's good for performance)list
).map(List::copyOf)
after mapToObj
in his solution (or .map(ArrayList::new)
if you want mutable results)Upvotes: 3
Reputation: 31878
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());
Upvotes: 7