diff --git a/core-java-modules/core-java-collections-list-3/README.md b/core-java-modules/core-java-collections-list-3/README.md new file mode 100644 index 0000000000..4948e293e6 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/README.md @@ -0,0 +1,14 @@ +## Java 核心(Core Java)集合中的 List 列表 (第3部分) + +This module contains articles about the Java List collection + +### Relevant Articles: +- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) +- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) +- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) +- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) +- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist) +- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference) +- [[<-- Prev]](/core-java-modules/core-java-collections-list-2) diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml new file mode 100644 index 0000000000..3777d61278 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + core-java-collections-list-3 + 0.1.0-SNAPSHOT + core-java-collections-list-3 + jar + + + com.ossez.core-java-modules + core-java-modules + 0.0.2-SNAPSHOT + ../pom.xml + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + net.sf.trove4j + trove4j + ${trove4j.version} + + + it.unimi.dsi + fastutil + ${fastutil.version} + + + colt + colt + ${colt.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + + + 3.0.2 + 8.1.0 + 1.2.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/allequalelements/VerifyAllEqualListElements.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/allequalelements/VerifyAllEqualListElements.java new file mode 100644 index 0000000000..64b16bad49 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/allequalelements/VerifyAllEqualListElements.java @@ -0,0 +1,55 @@ +package com.ossez.allequalelements; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import org.apache.commons.collections4.IterableUtils; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +public class VerifyAllEqualListElements { + + public boolean verifyAllEqualUsingALoop(List list) { + for (String s : list) { + if (!s.equals(list.get(0))) + return false; + } + return true; + } + + public boolean verifyAllEqualUsingHashSet(List list) { + return new HashSet(list).size() <= 1; + } + + public boolean verifyAllEqualUsingFrequency(List list) { + return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size(); + } + + public boolean verifyAllEqualUsingStream(List list) { + return list.stream() + .distinct() + .count() <= 1; + } + + public boolean verifyAllEqualAnotherUsingStream(List list) { + return list.isEmpty() || list.stream() + .allMatch(list.get(0)::equals); + } + + public boolean verifyAllEqualUsingGuava(List list) { + return Iterables.all(list, new Predicate() { + public boolean apply(String s) { + return s.equals(list.get(0)); + } + }); + } + + public boolean verifyAllEqualUsingApacheCommon(List list) { + return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate() { + public boolean evaluate(String s) { + return s.equals(list.get(0)); + } + }); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/collection/filtering/Employee.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/collection/filtering/Employee.java new file mode 100644 index 0000000000..5ca4e2929d --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/collection/filtering/Employee.java @@ -0,0 +1,44 @@ +package com.ossez.collection.filtering; + +/** + * Java 8 Collection Filtering by List of Values base class. + * + * @author Rodolfo Felipe + */ +public class Employee { + + private Integer employeeNumber; + private String name; + private Integer departmentId; + + public Employee(Integer employeeNumber, String name, Integer departmentId) { + this.employeeNumber = employeeNumber; + this.name = name; + this.departmentId = departmentId; + } + + public Integer getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(Integer employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getDepartmentId() { + return departmentId; + } + + public void setDepartmentId(Integer departmentId) { + this.departmentId = departmentId; + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/CopyListService.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/CopyListService.java new file mode 100644 index 0000000000..dbbe45d28a --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/CopyListService.java @@ -0,0 +1,73 @@ +package com.ossez.java.list; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CopyListService { + + public List copyListByConstructor(List source) { + return new ArrayList(source); + } + + public List copyListByConstructorAndEditOneFlowerInTheNewList(List source) { + List flowers = new ArrayList<>(source); + if(flowers.size() > 0) { + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); + } + + return flowers; + } + + public List copyListByAddAllMethod(List source) { + List flowers = new ArrayList<>(); + flowers.addAll(source); + return flowers; + } + + public List copyListByAddAllMethodAndEditOneFlowerInTheNewList(List source) { + List flowers = new ArrayList<>(); + flowers.addAll(source); + + if(flowers.size() > 0) { + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); + } + + return flowers; + } + + public List copyListByCopyMethod(List source, List dest) { + Collections.copy(dest, source); + return dest; + } + + public List copyListByStream(List source) { + return source.stream().collect(Collectors.toList()); + } + + public List copyListByStreamAndSkipFirstElement(List source) { + return source.stream().skip(1).collect(Collectors.toList()); + } + + public List copyListByStreamWithFilter(List source, Integer moreThanPetals) { + return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList()); + } + + public List copyListByStreamWithOptional(List source) { + return Optional.ofNullable(source) + .map(List::stream) + .orElseGet(Stream::empty) + .collect(Collectors.toList()); + } + + public List copyListByStreamWithOptionalAndSkip(List source) { + return Optional.ofNullable(source) + .map(List::stream) + .orElseGet(Stream::empty) + .skip(1) + .collect(Collectors.toList()); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/Flower.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/Flower.java new file mode 100644 index 0000000000..3b49f0ad84 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/java/list/Flower.java @@ -0,0 +1,28 @@ +package com.ossez.java.list; + +public class Flower { + + private String name; + private int petals; + + public Flower(String name, int petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPetals() { + return petals; + } + + public void setPetals(int petals) { + this.petals = petals; + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/duplicatescounter/DuplicatesCounter.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/duplicatescounter/DuplicatesCounter.java new file mode 100644 index 0000000000..50c857035a --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/duplicatescounter/DuplicatesCounter.java @@ -0,0 +1,52 @@ +package com.ossez.list.duplicatescounter; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Demo different approaches to get count of duplicated elements in an + * arrayList + */ +public class DuplicatesCounter { + + public static Map countByClassicalLoop(List inputList) { + Map resultMap = new HashMap<>(); + for (T element : inputList) { + if (resultMap.containsKey(element)) { + resultMap.put(element, resultMap.get(element) + 1L); + } else { + resultMap.put(element, 1L); + } + } + return resultMap; + } + + public static Map countByForEachLoopWithGetOrDefault(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapCompute(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L)); + return resultMap; + } + + public static Map countByForEachLoopWithMapMerge(List inputList) { + Map resultMap = new HashMap<>(); + inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum)); + return resultMap; + } + + public static Map countByStreamToMap(List inputList) { + return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum)); + } + + public static Map countByStreamGroupBy(List inputList) { + return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting())); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitiveCollections.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitiveCollections.java new file mode 100644 index 0000000000..535990fc0f --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitiveCollections.java @@ -0,0 +1,52 @@ +package com.ossez.list.primitive; + +import com.google.common.primitives.ImmutableIntArray; +import com.google.common.primitives.Ints; +import gnu.trove.list.array.TIntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; + +import java.util.Arrays; +import java.util.List; +import java.util.OptionalDouble; +import java.util.function.IntPredicate; +import java.util.stream.IntStream; + +public class PrimitiveCollections { + + public static void main(String[] args) { + + int[] primitives = new int[] {5, 10, 0, 2, -8}; + + guavaPrimitives(primitives); + + intStream(primitives); + + TIntArrayList tList = new TIntArrayList(primitives); + + cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives); + + IntArrayList fastUtilList = new IntArrayList(primitives); + + System.out.println(tList); + + System.out.println(coltList); + + System.out.println(fastUtilList); + } + + private static void intStream(int[] primitives) { + + IntStream stream = IntStream.of(5, 10, 0, 2, -8); + + IntStream newStream = IntStream.of(primitives); + + OptionalDouble average = stream.filter(i -> i > 0).average(); + } + + + private static void guavaPrimitives(int[] primitives) { + + ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build(); + System.out.println(immutableIntArray); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitivesListPerformance.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitivesListPerformance.java new file mode 100644 index 0000000000..60d67c7d45 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/main/java/com/ossez/list/primitive/PrimitivesListPerformance.java @@ -0,0 +1,97 @@ +package com.ossez.list.primitive; + +import it.unimi.dsi.fastutil.ints.IntArrayList; +import gnu.trove.list.array.TIntArrayList; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 100000, iterations = 10) +@Warmup(batchSize = 100000, iterations = 10) +@State(Scope.Thread) +public class PrimitivesListPerformance { + + private List arrayList = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); + private TIntArrayList tList = new TIntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + private IntArrayList fastUtilList = new IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + + private int getValue = 4; + + @Benchmark + public boolean addArrayList() { + return arrayList.add(getValue); + } + + @Benchmark + public boolean addTroveIntList() { + return tList.add(getValue); + } + + @Benchmark + public void addColtIntList() { + coltList.add(getValue); + } + + @Benchmark + public boolean addFastUtilIntList() { + return fastUtilList.add(getValue); + } + + @Benchmark + public int getArrayList() { + return arrayList.get(getValue); + } + + @Benchmark + public int getTroveIntList() { + return tList.get(getValue); + } + + @Benchmark + public int getColtIntList() { + return coltList.get(getValue); + } + + @Benchmark + public int getFastUtilIntList() { + return fastUtilList.getInt(getValue); + } + + @Benchmark + public boolean containsArrayList() { + return arrayList.contains(getValue); + } + + @Benchmark + public boolean containsTroveIntList() { + return tList.contains(getValue); + } + + @Benchmark + public boolean containsColtIntList() { + return coltList.contains(getValue); + } + + @Benchmark + public boolean containsFastUtilIntList() { + return fastUtilList.contains(getValue); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/main/resources/logback.xml b/core-java-modules/core-java-collections-list-3/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/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-3/src/test/java/com/ossez/allequalelements/VerifyAllEqualListElementsUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/allequalelements/VerifyAllEqualListElementsUnitTest.java new file mode 100644 index 0000000000..0447b03815 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/allequalelements/VerifyAllEqualListElementsUnitTest.java @@ -0,0 +1,172 @@ +package com.ossez.allequalelements; + +import org.junit.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class VerifyAllEqualListElementsUnitTest { + + private static List notAllEqualList = new ArrayList<>(); + + private static List emptyList = new ArrayList<>(); + + private static List allEqualList = new ArrayList<>(); + + static { + notAllEqualList = Arrays.asList("Jack", "James", "Sam", "James"); + emptyList = Arrays.asList(); + allEqualList = Arrays.asList("Jack", "Jack", "Jack", "Jack"); + } + + private static VerifyAllEqualListElements verifyAllEqualListElements = new VerifyAllEqualListElements(); + + @Test + public void givenNotAllEqualList_whenUsingALoop_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingALoop_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingALoop_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingALoop(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingHashSet_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingHashSet_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingHashSet_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingHashSet(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingFrequency_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingFrequency_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingFrequency_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingFrequency(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingStream_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingStream(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingAnotherStream_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingAnotherStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingAnotherStream_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualAnotherUsingStream(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingGuava_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingGuava_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingGuava_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingGuava(allEqualList); + + assertTrue(allEqual); + } + + @Test + public void givenNotAllEqualList_whenUsingApacheCommon_thenReturnFalse() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(notAllEqualList); + + assertFalse(allEqual); + } + + @Test + public void givenEmptyList_whenUsingApacheCommon_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(emptyList); + + assertTrue(allEqual); + } + + @Test + public void givenAllEqualList_whenUsingApacheCommon_thenReturnTrue() { + boolean allEqual = verifyAllEqualListElements.verifyAllEqualUsingApacheCommon(allEqualList); + + assertTrue(allEqual); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/CollectionsEmpty.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/CollectionsEmpty.java new file mode 100644 index 0000000000..84a724a19e --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/CollectionsEmpty.java @@ -0,0 +1,26 @@ +package com.ossez.collection; + +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; + +public class CollectionsEmpty { + + @Test + public void givenArrayList_whenAddingElement_addsNewElement() { + ArrayList mutableList = new ArrayList<>(); + mutableList.add("test"); + + Assert.assertEquals(mutableList.size(), 1); + Assert.assertEquals(mutableList.get(0), "test"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() { + List immutableList = Collections.emptyList(); + immutableList.add("test"); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/filtering/CollectionFilteringUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/filtering/CollectionFilteringUnitTest.java new file mode 100644 index 0000000000..0ad2b8d273 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/collection/filtering/CollectionFilteringUnitTest.java @@ -0,0 +1,73 @@ +package com.ossez.collection.filtering; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +/** + * Various filtering examples. + * + * @author Rodolfo Felipe + */ +public class CollectionFilteringUnitTest { + + private List buildEmployeeList() { + return Arrays.asList(new Employee(1, "Mike", 1), new Employee(2, "John", 1), new Employee(3, "Mary", 1), new Employee(4, "Joe", 2), new Employee(5, "Nicole", 2), new Employee(6, "Alice", 2), new Employee(7, "Bob", 3), new Employee(8, "Scarlett", 3)); + } + + private List employeeNameFilter() { + return Arrays.asList("Alice", "Mike", "Bob"); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() { + List filteredList = new ArrayList<>(); + List originalList = buildEmployeeList(); + List nameFilter = employeeNameFilter(); + + for (Employee employee : originalList) { + for (String name : nameFilter) { + if (employee.getName().equals(name)) { + filteredList.add(employee); + //break; + } + } + } + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambda() { + List filteredList; + List originalList = buildEmployeeList(); + List nameFilter = employeeNameFilter(); + + filteredList = originalList.stream() + .filter(employee -> nameFilter.contains(employee.getName())) + .collect(Collectors.toList()); + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilter.size())); + } + + @Test + public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingLambdaAndHashSet() { + List filteredList; + List originalList = buildEmployeeList(); + Set nameFilterSet = employeeNameFilter().stream() + .collect(Collectors.toSet()); + + filteredList = originalList.stream() + .filter(employee -> nameFilterSet.contains(employee.getName())) + .collect(Collectors.toList()); + + Assert.assertThat(filteredList.size(), Matchers.is(nameFilterSet.size())); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/java/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/java/list/CopyListServiceUnitTest.java new file mode 100644 index 0000000000..c4eefc1249 --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/java/list/CopyListServiceUnitTest.java @@ -0,0 +1,133 @@ +package com.ossez.java.list; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +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; + +public class CopyListServiceUnitTest { + + List flowers; + + private CopyListService copyListService; + + @Before + public void init() { + this.copyListService = new CopyListService(); + this.flowers = new ArrayList<>(); + + Flower poppy = new Flower("Poppy", 12); + flowers.add(poppy); + Flower anemone = new Flower("Anemone", 8); + flowers.add(anemone); + Flower catmint = new Flower("Catmint", 12); + flowers.add(catmint); + Flower diascia = new Flower("Diascia", 5); + flowers.add(diascia); + Flower iris = new Flower("Iris", 3); + flowers.add(iris); + Flower pansy = new Flower("Pansy", 5); + flowers.add(pansy); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() { + List copy = copyListService.copyListByConstructor(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() { + List copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() { + List copy = copyListService.copyListByAddAllMethod(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() { + List copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() { + List source = Arrays.asList(1,2,3); + List dest = Arrays.asList(4,5,6); + + dest = copyListService.copyListByCopyMethod(source, dest); + assertEquals(dest.size(), source.size()); + assertTrue(dest.containsAll(source)); + } + + @Test + public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() { + List source = Arrays.asList(1,2,3); + List dest = Arrays.asList(5,6,7,8,9,10); + + dest = copyListService.copyListByCopyMethod(source, dest); + assertNotEquals(dest.size(), source.size()); + assertTrue(dest.containsAll(source)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() { + List copy = copyListService.copyListByStream(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() { + List copy = copyListService.copyListByStreamAndSkipFirstElement(flowers); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 1, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() { + List copy = copyListService.copyListByStreamWithFilter(flowers, 5); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 3, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptional(null); + assertNotNull(copy); + assertEquals(copy.size(), 0); + } + + @Test + public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptional(flowers); + assertEquals(copy.size(), flowers.size()); + assertTrue(copy.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() { + List copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers); + assertNotEquals(copy.size(), flowers.size()); + assertEquals(copy.size() + 1, flowers.size()); + assertFalse(copy.containsAll(flowers)); + } +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/difference/FindDifferencesBetweenListsUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/difference/FindDifferencesBetweenListsUnitTest.java new file mode 100644 index 0000000000..6bdc0f6eae --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/difference/FindDifferencesBetweenListsUnitTest.java @@ -0,0 +1,96 @@ +package com.ossez.list.difference; + +import com.google.common.collect.Sets; +import org.apache.commons.collections4.CollectionUtils; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; +import static org.assertj.core.api.Assertions.*; + +public class FindDifferencesBetweenListsUnitTest { + + private static final List listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack"); + private static final List listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George"); + + @Test + public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() { + List differences = new ArrayList<>(listOne); + differences.removeAll(listTwo); + assertEquals(2, differences.size()); + assertThat(differences).containsExactly("Tom", "John"); + } + + @Test + public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() { + List differences = new ArrayList<>(listTwo); + differences.removeAll(listOne); + assertEquals(3, differences.size()); + assertThat(differences).containsExactly("Daniel", "Alan", "George"); + } + + @Test + public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() { + List differences = listOne.stream() + .filter(element -> !listTwo.contains(element)) + .collect(Collectors.toList()); + assertEquals(2, differences.size()); + assertThat(differences).containsExactly("Tom", "John"); + } + + @Test + public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() { + List differences = listTwo.stream() + .filter(element -> !listOne.contains(element)) + .collect(Collectors.toList()); + assertEquals(3, differences.size()); + assertThat(differences).containsExactly("Daniel", "Alan", "George"); + } + + @Test + public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() { + List differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo))); + assertEquals(2, differences.size()); + assertThat(differences).containsExactlyInAnyOrder("Tom", "John"); + } + + @Test + public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() { + List differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne))); + assertEquals(3, differences.size()); + assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George"); + } + + @Test + public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() { + List differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo))); + assertEquals(2, differences.size()); + assertThat(differences).containsExactly("Tom", "John"); + } + + @Test + public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() { + List differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne))); + assertEquals(3, differences.size()); + assertThat(differences).containsExactly("Daniel", "Alan", "George"); + } + + @Test + public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() { + List differences = new ArrayList<>(listOne); + listTwo.forEach(differences::remove); + assertThat(differences).containsExactly("Tom", "John", "Jack"); + } + + @Test + public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() { + List differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo)); + assertEquals(3, differences.size()); + assertThat(differences).containsExactly("Tom", "John", "Jack"); + } + +} diff --git a/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/duplicatescounter/DuplicatesCounterUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/duplicatescounter/DuplicatesCounterUnitTest.java new file mode 100644 index 0000000000..a27ab4835c --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/src/test/java/com/ossez/list/duplicatescounter/DuplicatesCounterUnitTest.java @@ -0,0 +1,65 @@ +package com.ossez.list.duplicatescounter; + +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.MapEntry.entry; + +class DuplicatesCounterUnitTest { + + private static List INPUT_LIST = Lists.list( + "expect1", + "expect2", "expect2", + "expect3", "expect3", "expect3", + "expect4", "expect4", "expect4", "expect4"); + + @Test + void givenInput_whenCountByClassicalLoop_thenGetResultMap() { + Map result = DuplicatesCounter.countByClassicalLoop(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() { + Map result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByStreamToMap_thenGetResultMap() { + Map result = DuplicatesCounter.countByStreamToMap(INPUT_LIST); + verifyResult(result); + } + + @Test + void givenInput_whenCountByStreamGroupBy_thenGetResultMap() { + Map result = DuplicatesCounter.countByStreamGroupBy(INPUT_LIST); + verifyResult(result); + } + + private void verifyResult(Map resultMap) { + assertThat(resultMap) + .isNotEmpty().hasSize(4) + .containsExactly( + entry("expect1", 1L), + entry("expect2", 2L), + entry("expect3", 3L), + entry("expect4", 4L)); + } +} \ No newline at end of file