P07 { public static <T> List<T> flatten_stream(List<?> list, Class<T> elementType) { return list .stream() .flatMap(e -> e instanceof List ? flatten_stream(((List<?>) e), elementType).stream() : Stream.of(e)) .map(e -> (T) e) .collect(toList()); }  static List<T> flatten(List<?> list, Class<T> elementType); static List<T> flatten_stream(List<?> list, Class<T> elementType);  }
@Test public void shouldFlattenAListOfList_stream() throws Exception { List<String> flatten = P07.flatten_stream(asList("a", asList("b", asList("c", "d")), "e"), String.class); assertThat(flatten, hasSize(5)); assertThat(flatten, hasItems("a", "b", "c", "d", "e")); }
@Test public void shouldFlattenDeepNestedLists_stream() throws Exception { List<String> flatten = P07.flatten_stream(asList("a", asList("b", asList("c", asList("d", "e", asList("f", "g"))), "h")), String.class); assertThat(flatten, hasSize(8)); assertThat(flatten, hasItems("a", "b", "c", "d", "e", "f", "g", "h")); }