P07 { public static <T> List<T> flatten(List<?> list, Class<T> elementType) { List<T> flatten = new ArrayList<>(); list.forEach(e -> { if (e instanceof List) { flatten.addAll(flatten((List<?>) e, elementType)); } else { flatten.add((T) e); } }); return flatten; }  static List<T> flatten(List<?> list, Class<T> elementType); static List<T> flatten_stream(List<?> list, Class<T> elementType);  }
@Test public void shouldFlattenAListOfList() throws Exception { List<String> flatten = P07.flatten(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() throws Exception { List<String> flatten = P07.flatten(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")); }
@Test public void shouldReturnEmptyListWhenTryingToFlattenAnEmptyList() throws Exception { List<String> flatten = P07.flatten(Collections.emptyList(), String.class); assertTrue(flatten.isEmpty()); }
@Test public void shouldReturnSameListWhenListHasNoNestedList() throws Exception { List<String> flatten = P07.flatten(asList("a", "b", "c", "d", "e"), String.class); assertThat(flatten, hasSize(5)); assertThat(flatten, hasItems("a", "b", "c", "d", "e")); }