diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md new file mode 100644 index 0000000000..77d583d7de --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -0,0 +1,15 @@ +## Java 核心(Core Java)集合中的 List 列表 (第2部分) + +This module contains articles about the Java List collection + +### Relevant Articles: +- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality) +- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items) +- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist) +- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception) +- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) +- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) +- [Flattening Nested Collections in Java](https://www.baeldung.com/java-flatten-nested-collections) +- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) +- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist) +- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3) diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml new file mode 100644 index 0000000000..fc022180db --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + core-java-collections-list-2 + 0.1.0-SNAPSHOT + core-java-collections-list-2 + jar + + + com.ossez.core-java-modules + core-java-modules + 0.0.2-SNAPSHOT + ../pom.xml + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/findastring/FindAStringInGivenList.java b/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/findastring/FindAStringInGivenList.java new file mode 100644 index 0000000000..1c6e5015ef --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/findastring/FindAStringInGivenList.java @@ -0,0 +1,72 @@ +package com.ossez.findastring; + +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import org.apache.commons.collections4.IterableUtils; +import org.apache.commons.collections4.IteratorUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class FindAStringInGivenList { + + + public List findUsingLoopWithRegex(String search, List list) { + + List matches = new ArrayList(); + + String pattern = ".*"+search+".*"; + Pattern p = Pattern.compile(pattern); + + for(String str: list) { + if (p.matcher(str).matches()) { + matches.add(str); + } + } + + return matches; + } + + + public List findUsingLoop(String search, List list) { + + List matches = new ArrayList(); + + for(String str: list) { + if (str.contains(search)) { + matches.add(str); + } + } + + return matches; + } + + public List findUsingStream(String search, List list) { + + List matchingElements = + list.stream() + .filter(str -> str.trim().contains(search)) + .collect(Collectors.toList()); + + return matchingElements; + } + + public List findUsingGuava(String search, List list) { + Iterable result = Iterables.filter(list, Predicates.containsPattern(search)); + + return Lists.newArrayList(result.iterator()); + } + + public List findUsingCommonsCollection(String search, List list) { + Iterable result = IterableUtils.filteredIterable(list, new org.apache.commons.collections4.Predicate() { + public boolean evaluate(String listElement) { + return listElement.contains(search); + } + }); + + return IteratorUtils.toList(result.iterator()); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/java/list/WaysToIterate.java b/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/java/list/WaysToIterate.java new file mode 100644 index 0000000000..26dddc9bf3 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/main/java/com/ossez/java/list/WaysToIterate.java @@ -0,0 +1,67 @@ +package com.ossez.java.list; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Demonstrates the different ways to loop over + * the elements of a list. + */ +public class WaysToIterate { + + List countries = Arrays.asList("Germany", "Panama", "Australia"); + + /** + * Iterate over a list using a basic for loop + */ + public void iterateWithForLoop() { + for (int i = 0; i < countries.size(); i++) { + System.out.println(countries.get(i)); + } + } + + /** + * Iterate over a list using the enhanced for loop + */ + public void iterateWithEnhancedForLoop() { + for (String country : countries) { + System.out.println(country); + } + } + + /** + * Iterate over a list using an Iterator + */ + public void iterateWithIterator() { + Iterator countriesIterator = countries.iterator(); + while(countriesIterator.hasNext()) { + System.out.println(countriesIterator.next()); + } + } + + /** + * Iterate over a list using a ListIterator + */ + public void iterateWithListIterator() { + ListIterator listIterator = countries.listIterator(); + while(listIterator.hasNext()) { + System.out.println(listIterator.next()); + } + } + + /** + * Iterate over a list using the Iterable.forEach() method + */ + public void iterateWithForEach() { + countries.forEach(System.out::println); + } + + /** + * Iterate over a list using the Stream.forEach() method + */ + public void iterateWithStreamForEach() { + countries.stream().forEach((c) -> System.out.println(c)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/main/resources/logback.xml b/core-java-modules/core-java-collections-list-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/array/converter/ArrayConvertToListUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/array/converter/ArrayConvertToListUnitTest.java new file mode 100644 index 0000000000..89b0bbcf53 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/array/converter/ArrayConvertToListUnitTest.java @@ -0,0 +1,116 @@ +package com.ossez.array.converter; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class ArrayConvertToListUnitTest { + + @Test + public void givenAnStringArray_whenConvertArrayToList_thenListCreated() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + } + + @Test + public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() { + int[] primitives = { 1, 2, 3, 4 }; + List numbers = Arrays.asList(primitives); + + assertNotNull(numbers); + assertEquals(numbers.size(), 1); + assertEquals(numbers.get(0), primitives); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.add("Celosia"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.remove("Poppy"); + } + + @Test + public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + List flowerList = Arrays.asList(flowers); + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + List newflowerList = new ArrayList<>(flowerList); + + assertNotNull(newflowerList); + assertEquals(newflowerList.size(), 4); + assertEquals(newflowerList.get(0), "Ageratum"); + assertEquals(newflowerList.get(1), "Allium"); + assertEquals(newflowerList.get(2), "Poppy"); + assertEquals(newflowerList.get(3), "Catmint"); + + newflowerList.add("Celosia"); + + assertEquals(newflowerList.size(), 5); + assertEquals(newflowerList.get(4), "Celosia"); + } + + @Test + public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() { + String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" }; + + List flowerList = new ArrayList<>(); + for(String flower: flowers) { + flowerList.add(flower); + } + + assertNotNull(flowerList); + assertEquals(flowerList.size(), 4); + + assertEquals(flowerList.get(0), "Ageratum"); + assertEquals(flowerList.get(1), "Allium"); + assertEquals(flowerList.get(2), "Poppy"); + assertEquals(flowerList.get(3), "Catmint"); + + flowerList.add("Celosia"); + + assertEquals(flowerList.size(), 5); + assertEquals(flowerList.get(4), "Celosia"); + } +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findItems/FindItemsBasedOnOtherStreamUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findItems/FindItemsBasedOnOtherStreamUnitTest.java new file mode 100644 index 0000000000..a33f253ba8 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findItems/FindItemsBasedOnOtherStreamUnitTest.java @@ -0,0 +1,88 @@ +package com.ossez.findItems; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class FindItemsBasedOnOtherStreamUnitTest { + + private List employeeList = new ArrayList(); + + private List departmentList = new ArrayList(); + + @Test + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; + + populate(employeeList, departmentList); + + List filteredList = employeeList.stream() + .filter(empl -> departmentList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) + .collect(Collectors.toList()); + + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); + } + + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); + + Collections.addAll(EmplList, employee1, employee2, employee3); + + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); + + Collections.addAll(deptList, department1, department2, department3); + } +} + +class Employee { + private Integer employeeId; + private String employeeName; + + Employee(Integer employeeId, String employeeName) { + super(); + this.employeeId = employeeId; + this.employeeName = employeeName; + } + + Integer getEmployeeId() { + return employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + +} + +class Department { + private Integer employeeId; + private String department; + + Department(Integer employeeId, String department) { + super(); + this.employeeId = employeeId; + this.department = department; + } + + Integer getEmployeeId() { + return employeeId; + } + + String getDepartment() { + return department; + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findastring/FindAStringInListUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findastring/FindAStringInListUnitTest.java new file mode 100644 index 0000000000..948777c644 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/findastring/FindAStringInListUnitTest.java @@ -0,0 +1,62 @@ +package com.ossez.findastring; + +import java.util.ArrayList; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.Test; +public class FindAStringInListUnitTest { + + private static List list = new ArrayList<>(); + + static { + list.add("Jack and Jill"); + list.add("James and Sarah"); + list.add("Sam and Louise"); + list.add("Jack"); + list.add(""); + } + + private static FindAStringInGivenList findAStringInGivenList = new FindAStringInGivenList(); + + @Test + public void givenAString_whenFoundUsingLoopWithRegex_thenReturnList() { + List matchingElements = findAStringInGivenList.findUsingLoopWithRegex("Jack", list); + assertEquals(2, matchingElements.size()); + assertEquals("Jack and Jill", matchingElements.get(0)); + assertEquals("Jack", matchingElements.get(1)); + } + + @Test + public void givenAString_whenFoundUsingLoop_thenReturnList() { + List matchingElements = findAStringInGivenList.findUsingLoop("Jack", list); + assertEquals(2, matchingElements.size()); + assertEquals("Jack and Jill", matchingElements.get(0)); + assertEquals("Jack", matchingElements.get(1)); + } + + + @Test + public void givenAString_whenFoundUsingStream_thenReturnList(){ + List matchingElements = findAStringInGivenList.findUsingStream("Jack", list); + assertEquals(2, matchingElements.size()); + assertEquals("Jack and Jill", matchingElements.get(0)); + assertEquals("Jack", matchingElements.get(1)); + } + + @Test + public void givenAString_whenFoundUsingCommonsCollection_thenReturnList(){ + List matchingElements = findAStringInGivenList.findUsingCommonsCollection("Jack", list); + assertEquals(2, matchingElements.size()); + assertEquals("Jack and Jill", matchingElements.get(0)); + assertEquals("Jack", matchingElements.get(1)); + } + + @Test + public void givenAString_whenFoundUsingGuava_thenReturnList(){ + List matchingElements = findAStringInGivenList.findUsingGuava("Jack", list); + assertEquals(2, matchingElements.size()); + assertEquals("Jack and Jill", matchingElements.get(0)); + assertEquals("Jack", matchingElements.get(1)); + } + +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListAssertJUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListAssertJUnitTest.java new file mode 100644 index 0000000000..d4a7796de8 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListAssertJUnitTest.java @@ -0,0 +1,23 @@ +package com.ossez.java.list; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ListAssertJUnitTest { + + private final List list1 = Arrays.asList("1", "2", "3", "4"); + private final List list2 = Arrays.asList("1", "2", "3", "4"); + private final List list3 = Arrays.asList("1", "2", "4", "3"); + + @Test + public void whenTestingForEquality_ShouldBeEqual() throws Exception { + assertThat(list1).isEqualTo(list2).isNotEqualTo(list3); + + assertThat(list1.equals(list2)).isTrue(); + assertThat(list1.equals(list3)).isFalse(); + } +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListJUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListJUnitTest.java new file mode 100644 index 0000000000..4566d7ebb7 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListJUnitTest.java @@ -0,0 +1,47 @@ +package com.ossez.java.list; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.HashSet; + +import java.util.stream.Collectors; + +public class ListJUnitTest { + + private final List list1 = Arrays.asList("1", "2", "3", "4"); + private final List list2 = Arrays.asList("1", "2", "3", "4"); + private final List list3 = Arrays.asList("1", "2", "4", "3"); + + @Test + public void whenTestingForEquality_ShouldBeEqual() throws Exception { + Assert.assertEquals(list1, list2); + Assert.assertNotSame(list1, list2); + Assert.assertNotEquals(list1, list3); + } + + @Test + public void whenIntersection_ShouldReturnCommonElements() throws Exception { + List list = Arrays.asList("red", "blue", "blue", "green", "red"); + List otherList = Arrays.asList("red", "green", "green", "yellow"); + + Set commonElements = new HashSet(Arrays.asList("red", "green")); + + Set result = list.stream() + .distinct() + .filter(otherList::contains) + .collect(Collectors.toSet()); + + Assert.assertEquals(commonElements, result); + + Set inverseResult = otherList.stream() + .distinct() + .filter(list::contains) + .collect(Collectors.toSet()); + + Assert.assertEquals(commonElements, inverseResult); + } +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListTestNgUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListTestNgUnitTest.java new file mode 100644 index 0000000000..a9c86adc8f --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/ListTestNgUnitTest.java @@ -0,0 +1,22 @@ +package com.ossez.java.list; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class ListTestNgUnitTest { + + private final List list1 = Arrays.asList("1", "2", "3", "4"); + private final List list2 = Arrays.asList("1", "2", "3", "4"); + private final List list3 = Arrays.asList("1", "2", "4", "3"); + + @Test + public void whenTestingForEquality_ShouldBeEqual() throws Exception { + assertEquals(list1, list2); + assertNotSame(list1, list2); + assertNotEquals(list1, list3); + } +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/WaysToIterateUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/WaysToIterateUnitTest.java new file mode 100644 index 0000000000..376e71c2ef --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/list/WaysToIterateUnitTest.java @@ -0,0 +1,71 @@ +package com.ossez.java.list; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import org.junit.Test; + +public class WaysToIterateUnitTest { + + List globalCountries = new ArrayList(); + List europeanCountries = Arrays.asList("Germany", "Panama", "Australia"); + + @Test + public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() { + for (int i = 0; i < europeanCountries.size(); i++) { + globalCountries.add(europeanCountries.get(i)); + } + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() { + for (String country : europeanCountries) { + globalCountries.add(country); + } + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() { + Iterator countriesIterator = europeanCountries.iterator(); + while (countriesIterator.hasNext()) { + globalCountries.add(countriesIterator.next()); + } + + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() { + ListIterator countriesIterator = europeanCountries.listIterator(); + while (countriesIterator.hasNext()) { + globalCountries.add(countriesIterator.next()); + } + + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() { + europeanCountries.forEach(country -> globalCountries.add(country)); + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } + + @Test + public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() { + europeanCountries.stream().forEach((country) -> globalCountries.add(country)); + assertEquals(globalCountries.size(), 3); + globalCountries.clear(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/listInitialization/ListInitializationUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/listInitialization/ListInitializationUnitTest.java new file mode 100644 index 0000000000..24f39da956 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/java/listInitialization/ListInitializationUnitTest.java @@ -0,0 +1,59 @@ +package com.ossez.java.listInitialization; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import lombok.extern.java.Log; + +import org.junit.Assert; +import org.junit.Test; + +@Log +public class ListInitializationUnitTest { + + @Test + public void givenAnonymousInnerClass_thenInitialiseList() { + List cities = new ArrayList() { + { + add("New York"); + add("Rio"); + add("Tokyo"); + } + }; + + Assert.assertTrue(cities.contains("New York")); + } + + @Test + public void givenArraysAsList_thenInitialiseList() { + List list = Arrays.asList("foo", "bar"); + + Assert.assertTrue(list.contains("foo")); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenArraysAsList_whenAdd_thenUnsupportedException() { + List list = Arrays.asList("foo", "bar"); + + list.add("baz"); + } + + @Test + public void givenArraysAsList_whenCreated_thenShareReference() { + String[] array = { "foo", "bar" }; + List list = Arrays.asList(array); + array[0] = "baz"; + Assert.assertEquals("baz", list.get(0)); + } + + @Test + public void givenStream_thenInitializeList() { + List list = Stream.of("foo", "bar") + .collect(Collectors.toList()); + + Assert.assertTrue(list.contains("foo")); + } +} diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/list/flattennestedlist/FlattenNestedListUnitTest.java b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/list/flattennestedlist/FlattenNestedListUnitTest.java new file mode 100644 index 0000000000..2370b7be69 --- /dev/null +++ b/core-java-modules/core-java-collections-list-2/src/test/java/com/ossez/list/flattennestedlist/FlattenNestedListUnitTest.java @@ -0,0 +1,50 @@ +package com.ossez.list.flattennestedlist; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import org.hamcrest.collection.IsIterableContainingInOrder; +import org.junit.Test; + +public class FlattenNestedListUnitTest { + private List> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four")); + + @Test + public void givenNestedList_thenFlattenImperatively() { + List ls = flattenListOfListsImperatively(lol); + + assertNotNull(ls); + assertTrue(ls.size() == 8); + // assert content + assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four")); + } + + @Test + public void givenNestedList_thenFlattenFunctionally() { + List ls = flattenListOfListsStream(lol); + + assertNotNull(ls); + assertTrue(ls.size() == 8); + // assert content + assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four")); + } + + private List flattenListOfListsImperatively(List> list) { + List ls = new ArrayList<>(); + list.forEach(ls::addAll); + return ls; + } + + private List flattenListOfListsStream(List> list) { + return list.stream() + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } +}