ttt
ttt

Reputation: 4004

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

Upvotes: 4

Views: 1955

Answers (2)

Tomasz Linkowski
Tomasz Linkowski

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:

  • nullpointer's solution has better performance (no new ArrayLists are created)
  • my solution is more readable (but you can always extract nullpointer's to a function like List<List<T>> sublists(List<T> list, int sublistSize)
  • my solution is independent of the original list while nullpointer's is a list of views of original list
    • usually, neither original list nor created sublists are modified afterwards so it doesn't matter (and it's good for performance)
    • however, if any were to be modified, nullpointer's solution will reflect those changes (or will even break if elements are removed from the original list)
    • to alleviate this, add an extra .map(List::copyOf) after mapToObj in his solution (or .map(ArrayList::new) if you want mutable results)

Upvotes: 3

Naman
Naman

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

Related Questions