diff --git a/core-java/0.8260098203820962 b/core-java/0.8260098203820962 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/main/java/com/baeldung/list/flattennestedlist/FlattenNestedList.java b/core-java/src/main/java/com/baeldung/list/flattennestedlist/FlattenNestedList.java new file mode 100644 index 0000000000..11ee66560b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/list/flattennestedlist/FlattenNestedList.java @@ -0,0 +1,17 @@ +package com.baeldung.list.flattennestedlist; + +import java.util.ArrayList; +import java.util.List; + +public class FlattenNestedList { + + public List flattenListOfLists(List> lol) { + + // flatten the list + List ls = new ArrayList<>(); + lol.forEach((k) -> ls.addAll(k)); + + return ls; + } + +} diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java new file mode 100644 index 0000000000..09bfdae9a5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java @@ -0,0 +1,52 @@ +package com.baeldung.list.flattennestedlist; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FlattenNestedListTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(FlattenNestedListTest.class); + private FlattenNestedList flol; + + @Before + public void setup() { + flol = new FlattenNestedList(); + } + + @Test + public void givenListOfListOfString_flattenNestedList() { + + // create the list to flatten + List ls1 = Arrays.asList("one:one", "one:two", "one:three"); + List ls2 = Arrays.asList("two:one", "two:two", "two:three"); + List ls3 = Arrays.asList("three:one", "three:two", "three:three"); + + List> lol = new ArrayList<>(); + lol.addAll(Arrays.asList(ls1, ls2, ls3)); + + // show nested list + LOGGER.debug("\nNested list: "); + lol.forEach((nl) -> LOGGER.debug(nl + "")); + + // flatten it + List ls = flol.flattenListOfLists(lol); + + assertNotNull(ls); + assertTrue(ls.size() == 9); + + // show flattened list + LOGGER.debug("\nFlattened list:"); + ls.forEach((l) -> LOGGER.debug(l)); + + } + +}