リストと連続させる数を指定して、List の List で結果を求める。
public static <T> List<List<T>> lengthSequencelist(List<T> list, int length){ int last = list.size() - length + 1; return Stream.concat( IntStream.range(0, last).boxed().map(i->list.subList(i, i + length)) , IntStream.range(last, list.size()).boxed().map(i->list.subList(i, list.size())) ).collect(Collectors.toList()); }
"A"~"Z" のリスト
List<String> list = Arrays.asList("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
連続7個の組みで、リストを作成
lengthSequencelist(list, 7).stream().forEach(System.out::println);
結果
[A, B, C, D, E, F, G] [B, C, D, E, F, G, H] [C, D, E, F, G, H, I] [D, E, F, G, H, I, J] [E, F, G, H, I, J, K] [F, G, H, I, J, K, L] [G, H, I, J, K, L, M] [H, I, J, K, L, M, N] [I, J, K, L, M, N, O] [J, K, L, M, N, O, P] [K, L, M, N, O, P, Q] [L, M, N, O, P, Q, R] [M, N, O, P, Q, R, S] [N, O, P, Q, R, S, T] [O, P, Q, R, S, T, U] [P, Q, R, S, T, U, V] [Q, R, S, T, U, V, W] [R, S, T, U, V, W, X] [S, T, U, V, W, X, Y] [T, U, V, W, X, Y, Z] [U, V, W, X, Y, Z] [V, W, X, Y, Z] [W, X, Y, Z] [X, Y, Z] [Y, Z] [Z]
Stream<List<T>> を求める場合、
public static <T> Stream<List<T>> lengthSequenceStream(List<T> list, int length){ int last = list.size() - length + 1; return Stream.concat( IntStream.range(0, last).boxed().map(i->list.subList(i, i + length)) , IntStream.range(last, list.size()).boxed().map(i->list.subList(i, list.size())) ); }
lengthSequenceStream(list, 7).forEach(System.out::println);