Java 核心(Core Java)集合中的 List 列表 (第3部分)的内容

This commit is contained in:
YuCheng Hu 2022-05-02 12:22:02 -04:00
parent 8916057acb
commit bf0b4e4c7e
16 changed files with 1050 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-list-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>net.sf.trove4j</groupId>
<artifactId>trove4j</artifactId>
<version>${trove4j.version}</version>
</dependency>
<dependency>
<groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId>
<version>${fastutil.version}</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<properties>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
</properties>
</project>

View File

@ -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<String> list) {
for (String s : list) {
if (!s.equals(list.get(0)))
return false;
}
return true;
}
public boolean verifyAllEqualUsingHashSet(List<String> list) {
return new HashSet<String>(list).size() <= 1;
}
public boolean verifyAllEqualUsingFrequency(List<String> list) {
return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size();
}
public boolean verifyAllEqualUsingStream(List<String> list) {
return list.stream()
.distinct()
.count() <= 1;
}
public boolean verifyAllEqualAnotherUsingStream(List<String> list) {
return list.isEmpty() || list.stream()
.allMatch(list.get(0)::equals);
}
public boolean verifyAllEqualUsingGuava(List<String> list) {
return Iterables.all(list, new Predicate<String>() {
public boolean apply(String s) {
return s.equals(list.get(0));
}
});
}
public boolean verifyAllEqualUsingApacheCommon(List<String> list) {
return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() {
public boolean evaluate(String s) {
return s.equals(list.get(0));
}
});
}
}

View File

@ -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;
}
}

View File

@ -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<Flower> copyListByConstructor(List<Flower> source) {
return new ArrayList<Flower>(source);
}
public List<Flower> copyListByConstructorAndEditOneFlowerInTheNewList(List<Flower> source) {
List<Flower> flowers = new ArrayList<>(source);
if(flowers.size() > 0) {
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
}
return flowers;
}
public List<Flower> copyListByAddAllMethod(List<Flower> source) {
List<Flower> flowers = new ArrayList<>();
flowers.addAll(source);
return flowers;
}
public List<Flower> copyListByAddAllMethodAndEditOneFlowerInTheNewList(List<Flower> source) {
List<Flower> flowers = new ArrayList<>();
flowers.addAll(source);
if(flowers.size() > 0) {
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
}
return flowers;
}
public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) {
Collections.copy(dest, source);
return dest;
}
public List<Flower> copyListByStream(List<Flower> source) {
return source.stream().collect(Collectors.toList());
}
public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) {
return source.stream().skip(1).collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) {
return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithOptional(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList());
}
public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) {
return Optional.ofNullable(source)
.map(List::stream)
.orElseGet(Stream::empty)
.skip(1)
.collect(Collectors.toList());
}
}

View File

@ -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;
}
}

View File

@ -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 <T> Map<T, Long> countByClassicalLoop(List<T> inputList) {
Map<T, Long> 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 <T> Map<T, Long> countByForEachLoopWithGetOrDefault(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.put(e, resultMap.getOrDefault(e, 0L) + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapCompute(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.compute(e, (k, v) -> v == null ? 1L : v + 1L));
return resultMap;
}
public static <T> Map<T, Long> countByForEachLoopWithMapMerge(List<T> inputList) {
Map<T, Long> resultMap = new HashMap<>();
inputList.forEach(e -> resultMap.merge(e, 1L, Long::sum));
return resultMap;
}
public static <T> Map<T, Long> countByStreamToMap(List<T> inputList) {
return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
}
public static <T> Map<T, Long> countByStreamGroupBy(List<T> inputList) {
return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting()));
}
}

View File

@ -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);
}
}

View File

@ -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<Integer> 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();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -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<String> notAllEqualList = new ArrayList<>();
private static List<String> emptyList = new ArrayList<>();
private static List<String> 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);
}
}

View File

@ -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<String> 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<String> immutableList = Collections.emptyList();
immutableList.add("test");
}
}

View File

@ -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<Employee> 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<String> employeeNameFilter() {
return Arrays.asList("Alice", "Mike", "Bob");
}
@Test
public void givenEmployeeList_andNameFilterList_thenObtainFilteredEmployeeList_usingForEachLoop() {
List<Employee> filteredList = new ArrayList<>();
List<Employee> originalList = buildEmployeeList();
List<String> 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<Employee> filteredList;
List<Employee> originalList = buildEmployeeList();
List<String> 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<Employee> filteredList;
List<Employee> originalList = buildEmployeeList();
Set<String> 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()));
}
}

View File

@ -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<Flower> 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<Flower> copy = copyListService.copyListByConstructor(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() {
List<Flower> copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethod(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> 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<Integer> source = Arrays.asList(1,2,3);
List<Integer> 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<Flower> copy = copyListService.copyListByStream(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> 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<Flower> 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<Flower> copy = copyListService.copyListByStreamWithOptional(null);
assertNotNull(copy);
assertEquals(copy.size(), 0);
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptional(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 1, flowers.size());
assertFalse(copy.containsAll(flowers));
}
}

View File

@ -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<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listOne);
differences.removeAll(listTwo);
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listTwo);
differences.removeAll(listOne);
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
List<String> 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<String> 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<String> 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<String> 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<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(listOne);
listTwo.forEach(differences::remove);
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
@Test
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
}

View File

@ -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<String> INPUT_LIST = Lists.list(
"expect1",
"expect2", "expect2",
"expect3", "expect3", "expect3",
"expect4", "expect4", "expect4", "expect4");
@Test
void givenInput_whenCountByClassicalLoop_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByClassicalLoop(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithGetOrDefault_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithGetOrDefault(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithMapCompute_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapCompute(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByForEachLoopWithMapMerge_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByForEachLoopWithMapMerge(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByStreamToMap_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByStreamToMap(INPUT_LIST);
verifyResult(result);
}
@Test
void givenInput_whenCountByStreamGroupBy_thenGetResultMap() {
Map<String, Long> result = DuplicatesCounter.countByStreamGroupBy(INPUT_LIST);
verifyResult(result);
}
private void verifyResult(Map<String, Long> resultMap) {
assertThat(resultMap)
.isNotEmpty().hasSize(4)
.containsExactly(
entry("expect1", 1L),
entry("expect2", 2L),
entry("expect3", 3L),
entry("expect4", 4L));
}
}