diff --git a/core-java-modules/core-java-collections-list/README.md b/core-java-modules/core-java-collections-list/README.md new file mode 100644 index 0000000000..ff7a9876a2 --- /dev/null +++ b/core-java-modules/core-java-collections-list/README.md @@ -0,0 +1,15 @@ +## Core Java Collections List + +This module contains articles about the Java List collection + +### Relevant Articles: +- [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element) +- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list) +- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list) +- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) +- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) +- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) +- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) +- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) +- [[Next -->]](/core-java-modules/core-java-collections-list-2) diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml new file mode 100644 index 0000000000..d62275ab6d --- /dev/null +++ b/core-java-modules/core-java-collections-list/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + core-java-collections-list + 0.1.0-SNAPSHOT + core-java-collections-list + jar + + + com.ossez.core-java-modules + core-java-modules + 0.0.2-SNAPSHOT + + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java new file mode 100644 index 0000000000..6807a6642b --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java @@ -0,0 +1,37 @@ +package com.baeldung.findanelement; + +public class Customer { + + private int id; + private String name; + + public Customer(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + return id * 20; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Customer) { + Customer otherCustomer = (Customer) obj; + if (id == otherCustomer.id) + return true; + } + return false; + } + + +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java new file mode 100644 index 0000000000..b2d4250f6b --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java @@ -0,0 +1,77 @@ +package com.baeldung.findanelement; + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.collections4.IterableUtils; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +public class FindACustomerInGivenList { + + public Customer findUsingGivenIndex(int indexOfCustomer, List customers) { + if (indexOfCustomer >= 0 && indexOfCustomer < customers.size()) + return customers.get(indexOfCustomer); + return null; + } + + public int findUsingIndexOf(Customer customer, List customers) { + return customers.indexOf(customer); + } + + public boolean findUsingContains(Customer customer, List customers) { + return customers.contains(customer); + } + + public Customer findUsingIterator(String name, List customers) { + Iterator iterator = customers.iterator(); + while (iterator.hasNext()) { + Customer customer = iterator.next(); + if (customer.getName().equals(name)) { + return customer; + } + } + return null; + } + + public Customer findUsingEnhancedForLoop(String name, List customers) { + for (Customer customer : customers) { + if (customer.getName().equals(name)) { + return customer; + } + } + return null; + } + + public Customer findUsingStream(String name, List customers) { + return customers.stream() + .filter(customer -> customer.getName().equals(name)) + .findFirst() + .orElse(null); + } + + public Customer findUsingParallelStream(String name, List customers) { + return customers.parallelStream() + .filter(customer -> customer.getName().equals(name)) + .findAny() + .orElse(null); + } + + public Customer findUsingGuava(String name, List customers) { + return Iterables.tryFind(customers, new Predicate() { + public boolean apply(Customer customer) { + return customer.getName().equals(name); + } + }).orNull(); + } + + public Customer findUsingApacheCommon(String name, List customers) { + return IterableUtils.find(customers, new org.apache.commons.collections4.Predicate() { + public boolean evaluate(Customer customer) { + return customer.getName().equals(name); + } + }); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java new file mode 100644 index 0000000000..8b91fca32f --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java @@ -0,0 +1,210 @@ +package com.baeldung.java.list; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +public class CustomList implements List { + private Object[] internal = {}; + + @Override + public boolean isEmpty() { + // the first cycle + // return true; + + // the second cycle + // if (internal.length != 0) { + // return false; + // } else { + // return true; + // } + + // refactoring + return internal.length == 0; + } + + @Override + public int size() { + // the first cycle + // if (isEmpty()) { + // return 0; + // } else { + // return internal.length; + // } + + // refactoring + return internal.length; + } + + @SuppressWarnings("unchecked") + @Override + public E get(int index) { + // the first cycle + // return (E) internal[0]; + + // improvement + return (E) internal[index]; + } + + @Override + public boolean add(E element) { + // the first cycle + // internal = new Object[] { element }; + // return true; + + // the second cycle + Object[] temp = Arrays.copyOf(internal, internal.length + 1); + temp[internal.length] = element; + internal = temp; + return true; + } + + @Override + public void add(int index, E element) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(int index, Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public E remove(int index) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean remove(Object object) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(Collection collection) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean contains(Object object) { + for (Object element : internal) { + if (object.equals(element)) { + return true; + } + } + return false; + } + + @Override + public boolean containsAll(Collection collection) { + for (Object element : collection) + if (!contains(element)) { + return false; + } + return true; + } + + @SuppressWarnings("unchecked") + @Override + public E set(int index, E element) { + E oldElement = (E) internal[index]; + internal[index] = element; + return oldElement; + } + + @Override + public void clear() { + internal = new Object[0]; + } + + @Override + public int indexOf(Object object) { + for (int i = 0; i < internal.length; i++) { + if (object.equals(internal[i])) { + return i; + } + } + return -1; + } + + @Override + public int lastIndexOf(Object object) { + for (int i = internal.length - 1; i >= 0; i--) { + if (object.equals(internal[i])) { + return i; + } + } + return -1; + } + + @SuppressWarnings("unchecked") + @Override + public List subList(int fromIndex, int toIndex) { + Object[] temp = new Object[toIndex - fromIndex]; + System.arraycopy(internal, fromIndex, temp, 0, temp.length); + return (List) Arrays.asList(temp); + } + + @Override + public Object[] toArray() { + return Arrays.copyOf(internal, internal.length); + } + + @SuppressWarnings("unchecked") + @Override + public T[] toArray(T[] array) { + if (array.length < internal.length) { + return (T[]) Arrays.copyOf(internal, internal.length, array.getClass()); + } + + System.arraycopy(internal, 0, array, 0, internal.length); + if (array.length > internal.length) { + array[internal.length] = null; + } + return array; + } + + @Override + public Iterator iterator() { + return new CustomIterator(); + } + + @Override + public ListIterator listIterator() { + return null; + } + + @Override + public ListIterator listIterator(int index) { + // ignored for brevity + return null; + } + + private class CustomIterator implements Iterator { + int index; + + @Override + public boolean hasNext() { + return index != internal.length; + } + + @SuppressWarnings("unchecked") + @Override + public E next() { + E element = (E) CustomList.this.internal[index]; + index++; + return element; + } + } +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java new file mode 100644 index 0000000000..42dd543ed4 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java @@ -0,0 +1,80 @@ +package com.baeldung.java.list; + +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.collections4.iterators.ReverseListIterator; + +import com.google.common.collect.Lists; + +/** + * Provides methods for iterating backward over a list. + */ +public class ReverseIterator { + + /** + * Iterate using the for loop. + * + * @param list the list + */ + public void iterateUsingForLoop(final List list) { + + for (int i = list.size(); i-- > 0; ) { + System.out.println(list.get(i)); + } + } + + /** + * Iterate using the Java {@link ListIterator}. + * + * @param list the list + */ + public void iterateUsingListIterator(final List list) { + + final ListIterator listIterator = list.listIterator(list.size()); + while (listIterator.hasPrevious()) { + System.out.println(listIterator.previous()); + } + } + + /** + * Iterate using Java {@link Collections} API. + * + * @param list the list + */ + public void iterateUsingCollections(final List list) { + + Collections.reverse(list); + for (final String item : list) { + System.out.println(item); + } + } + + /** + * Iterate using Apache Commons {@link ReverseListIterator}. + * + * @param list the list + */ + public void iterateUsingApacheReverseListIterator(final List list) { + + final ReverseListIterator listIterator = new ReverseListIterator(list); + while (listIterator.hasNext()) { + System.out.println(listIterator.next()); + } + } + + /** + * Iterate using Guava {@link Lists} API. + * + * @param list the list + */ + public void iterateUsingGuava(final List list) { + + final List reversedList = Lists.reverse(list); + for (final String item : reversedList) { + System.out.println(item); + } + } + +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java new file mode 100644 index 0000000000..139475bc25 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java @@ -0,0 +1,31 @@ +package com.baeldung.java_8_features; + +public class Car { + + private String model; + private int topSpeed; + + public Car(String model, int topSpeed) { + super(); + this.model = model; + this.topSpeed = topSpeed; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public int getTopSpeed() { + return topSpeed; + } + + public void setTopSpeed(int topSpeed) { + this.topSpeed = topSpeed; + } + + +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java new file mode 100644 index 0000000000..83b5530ee8 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java @@ -0,0 +1,27 @@ +package com.baeldung.java_8_features; + +public class Person { + private String name; + private Integer age; + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/Flower.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/Flower.java new file mode 100644 index 0000000000..29c6a78326 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.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/src/main/java/com/baeldung/list/listoflist/Pen.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pen.java new file mode 100644 index 0000000000..efbd88d0b1 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pen.java @@ -0,0 +1,18 @@ +package com.baeldung.list.listoflist; + +public class Pen implements Stationery { + + public String name; + + public Pen(String name) { + this.name = name; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java new file mode 100644 index 0000000000..7dfa119703 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java @@ -0,0 +1,18 @@ +package com.baeldung.list.listoflist; + +public class Pencil implements Stationery{ + + public String name; + + public Pencil(String name) { + this.name = name; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java new file mode 100644 index 0000000000..7511139e14 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java @@ -0,0 +1,18 @@ +package com.baeldung.list.listoflist; + +public class Rubber implements Stationery { + + public String name; + + public Rubber(String name) { + this.name = name; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java new file mode 100644 index 0000000000..d914397cb8 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java @@ -0,0 +1,5 @@ +package com.baeldung.list.listoflist; + +public interface Stationery { + +} diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java new file mode 100644 index 0000000000..d5f9cf4b4e --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java @@ -0,0 +1,111 @@ +package com.baeldung.list.removeall; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class RemoveAll { + + static void removeWithWhileLoopPrimitiveElement(List list, int element) { + while (list.contains(element)) { + list.remove(element); + } + } + + static void removeWithWhileLoopNonPrimitiveElement(List list, Integer element) { + while (list.contains(element)) { + list.remove(element); + } + } + + static void removeWithWhileLoopStoringFirstOccurrenceIndex(List list, Integer element) { + int index; + while ((index = list.indexOf(element)) >= 0) { + list.remove(index); + } + } + + static void removeWithCallingRemoveUntilModifies(List list, Integer element) { + while (list.remove(element)) + ; + } + + static void removeWithStandardForLoopUsingIndex(List list, int element) { + for (int i = 0; i < list.size(); i++) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + } + } + } + + static void removeWithForLoopDecrementOnRemove(List list, int element) { + for (int i = 0; i < list.size(); i++) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + i--; + } + } + } + + static void removeWithForLoopIncrementIfRemains(List list, int element) { + for (int i = 0; i < list.size();) { + if (Objects.equals(element, list.get(i))) { + list.remove(i); + } else { + i++; + } + } + } + + static void removeWithForEachLoop(List list, int element) { + for (Integer number : list) { + if (Objects.equals(number, element)) { + list.remove(number); + } + } + } + + static void removeWithIterator(List list, int element) { + for (Iterator i = list.iterator(); i.hasNext();) { + Integer number = i.next(); + if (Objects.equals(number, element)) { + i.remove(); + } + } + } + + static List removeWithCollectingAndReturningRemainingElements(List list, int element) { + List remainingElements = new ArrayList<>(); + for (Integer number : list) { + if (!Objects.equals(number, element)) { + remainingElements.add(number); + } + } + return remainingElements; + } + + static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List list, int element) { + List remainingElements = new ArrayList<>(); + for (Integer number : list) { + if (!Objects.equals(number, element)) { + remainingElements.add(number); + } + } + + list.clear(); + list.addAll(remainingElements); + } + + static List removeWithStreamFilter(List list, Integer element) { + return list.stream() + .filter(e -> !Objects.equals(e, element)) + .collect(Collectors.toList()); + } + + static void removeWithRemoveIf(List list, Integer element) { + list.removeIf(n -> Objects.equals(n, element)); + } + +} diff --git a/core-java-modules/core-java-collections-list/src/main/resources/logback.xml b/core-java-modules/core-java-collections-list/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-collections-list/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/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java new file mode 100644 index 0000000000..5ef08a9337 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.collections; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsInRelativeOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.PredicateUtils; +import org.junit.Test; + +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +public class JavaCollectionCleanupUnitTest { + + // tests - removing nulls + + @Test + public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() { + final List list = Lists.newArrayList(null, 1, null); + while (list.remove(null)) + ; + + assertThat(list, hasSize(1)); + } + + @Test + public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() { + final List list = Lists.newArrayList(null, 1, null); + list.removeAll(Collections.singleton(null)); + + assertThat(list, hasSize(1)); + } + + @Test + public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() { + final List list = Lists.newArrayList(null, 1, null); + Iterables.removeIf(list, Predicates.isNull()); + + assertThat(list, hasSize(1)); + } + + @Test + public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() { + final List list = Lists.newArrayList(null, 1, null, 2, 3); + final List listWithoutNulls = Lists.newArrayList(Iterables.filter(list, Predicates.notNull())); + + assertThat(listWithoutNulls, hasSize(3)); + } + + @Test + public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() { + final List list = Lists.newArrayList(null, 1, 2, null, 3, null); + CollectionUtils.filter(list, PredicateUtils.notNullPredicate()); + + assertThat(list, hasSize(3)); + } + + // tests - remove duplicates + + @Test + public void givenListContainsDuplicates_whenRemovingDuplicatesWithPlainJava_thenCorrect() { + final List listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0); + final List listWithoutDuplicates = new ArrayList<>(new HashSet<>(listWithDuplicates)); + + assertThat(listWithoutDuplicates, hasSize(5)); + assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2)); + } + + @Test + public void givenListContainsDuplicates_whenRemovingDuplicatesPreservingOrderWithPlainJava_thenCorrect() { + final List listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0); + final List listWithoutDuplicates = new ArrayList<>(new LinkedHashSet<>(listWithDuplicates)); + + assertThat(listWithoutDuplicates, hasSize(5)); + assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2)); + } + + @Test + public void givenListContainsDuplicates_whenRemovingDuplicatesWithGuava_thenCorrect() { + final List listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0); + final List listWithoutDuplicates = Lists.newArrayList(Sets.newHashSet(listWithDuplicates)); + + assertThat(listWithoutDuplicates, hasSize(5)); + assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2)); + } + + @Test + public void givenListContainsDuplicates_whenRemovingDuplicatesPreservingOrderWithGuava_thenCorrect() { + final List listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0); + final List listWithoutDuplicates = Lists.newArrayList(Sets.newLinkedHashSet(listWithDuplicates)); + + assertThat(listWithoutDuplicates, hasSize(5)); + assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2)); + } +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java new file mode 100644 index 0000000000..3c96cf1392 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java @@ -0,0 +1,158 @@ +package com.baeldung.findanelement; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class FindACustomerInGivenListUnitTest { + + private static List customers = new ArrayList<>(); + + static { + customers.add(new Customer(1, "Jack")); + customers.add(new Customer(2, "James")); + customers.add(new Customer(3, "Sam")); + } + + private static FindACustomerInGivenList findACustomerInGivenList = new FindACustomerInGivenList(); + + @Test + public void givenAnIndex_whenFoundUsingGivenIndex_thenReturnCustomer() { + Customer customer = findACustomerInGivenList.findUsingGivenIndex(0, customers); + + assertEquals(1, customer.getId()); + } + + @Test + public void givenAnIndex_whenNotFoundUsingGivenIndex_thenReturnNull() { + Customer customer = findACustomerInGivenList.findUsingGivenIndex(5, customers); + + assertNull(customer); + } + + @Test + public void givenACustomer_whenFoundUsingContains_thenReturnTrue() { + Customer james = new Customer(2, "James"); + boolean isJamesPresent = findACustomerInGivenList.findUsingContains(james, customers); + + assertEquals(true, isJamesPresent); + } + + @Test + public void givenACustomer_whenNotFoundUsingContains_thenReturnFalse() { + Customer john = new Customer(5, "John"); + boolean isJohnPresent = findACustomerInGivenList.findUsingContains(john, customers); + + assertEquals(false, isJohnPresent); + } + + @Test + public void givenACustomer_whenFoundUsingIndexOf_thenReturnItsIndex() { + Customer james = new Customer(2, "James"); + int indexOfJames = findACustomerInGivenList.findUsingIndexOf(james, customers); + + assertEquals(1, indexOfJames); + } + + @Test + public void givenACustomer_whenNotFoundUsingIndexOf_thenReturnMinus1() { + Customer john = new Customer(5, "John"); + int indexOfJohn = findACustomerInGivenList.findUsingIndexOf(john, customers); + + assertEquals(-1, indexOfJohn); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingIterator_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingIterator("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingIterator_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingIterator("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingEnhancedFor_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingEnhancedForLoop("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingEnhancedFor_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingEnhancedForLoop("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingStream_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingStream("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingStream_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingStream("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingParallelStream_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingParallelStream("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingParallelStream_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingParallelStream("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingApacheCommon_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingApacheCommon("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingApacheCommon_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingApacheCommon("John", customers); + + assertNull(john); + } + + @Test + public void givenName_whenCustomerWithNameFoundUsingGuava_thenReturnCustomer() { + Customer james = findACustomerInGivenList.findUsingGuava("James", customers); + + assertEquals("James", james.getName()); + assertEquals(2, james.getId()); + } + + @Test + public void givenName_whenCustomerWithNameNotFoundUsingGuava_thenReturnNull() { + Customer john = findACustomerInGivenList.findUsingGuava("John", customers); + + assertNull(john); + } + +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java new file mode 100644 index 0000000000..9ea42e88e8 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java @@ -0,0 +1,296 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; + +public class CustomListUnitTest { + @Test + public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() { + List list = new CustomList<>(); + + assertTrue(list.isEmpty()); + } + + @Test + public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() { + List list = new CustomList<>(); + list.add(null); + + assertFalse(list.isEmpty()); + } + + @Test + public void givenListWithAnElement_whenSize_thenOneIsReturned() { + List list = new CustomList<>(); + list.add(null); + + assertEquals(1, list.size()); + } + + @Test + public void givenListWithAnElement_whenGet_thenThatElementIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + Object element = list.get(0); + + assertEquals("baeldung", element); + } + + @Test + public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() { + List list = new CustomList<>(); + boolean succeeded = list.add(null); + + assertTrue(succeeded); + } + + @Test + public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add(".com"); + Object element1 = list.get(0); + Object element2 = list.get(1); + + assertEquals("baeldung", element1); + assertEquals(".com", element2); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenAddToSpecifiedIndex_thenExceptionIsThrown() { + new CustomList<>().add(0, null); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenAddAllToTheEnd_thenExceptionIsThrown() { + Collection collection = new ArrayList<>(); + List list = new CustomList<>(); + list.addAll(collection); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenAddAllToSpecifiedIndex_thenExceptionIsThrown() { + Collection collection = new ArrayList<>(); + List list = new CustomList<>(); + list.addAll(0, collection); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenRemoveAtSpecifiedIndex_thenExceptionIsThrown() { + List list = new CustomList<>(); + list.add("baeldung"); + list.remove(0); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenRemoveSpecifiedElement_thenExceptionIsThrown() { + List list = new CustomList<>(); + list.add("baeldung"); + list.remove("baeldung"); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenRemoveAll_thenExceptionIsThrown() { + Collection collection = new ArrayList<>(); + collection.add("baeldung"); + List list = new CustomList<>(); + list.removeAll(collection); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenRetainAll_thenExceptionIsThrown() { + Collection collection = new ArrayList<>(); + collection.add("baeldung"); + List list = new CustomList<>(); + list.add("baeldung"); + list.retainAll(collection); + } + + @Test + public void givenEmptyList_whenContains_thenFalseIsReturned() { + List list = new CustomList<>(); + + assertFalse(list.contains(null)); + } + + @Test + public void givenListWithAnElement_whenContains_thenTrueIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + + assertTrue(list.contains("baeldung")); + } + + @Test + public void givenListWithAnElement_whenContainsAll_thenTrueIsReturned() { + Collection collection = new ArrayList<>(); + collection.add("baeldung"); + List list = new CustomList<>(); + list.add("baeldung"); + + assertTrue(list.containsAll(collection)); + } + + @Test + public void givenList_whenContainsAll_thenEitherTrueOrFalseIsReturned() { + Collection collection1 = new ArrayList<>(); + collection1.add("baeldung"); + collection1.add(".com"); + Collection collection2 = new ArrayList<>(); + collection2.add("baeldung"); + + List list = new CustomList<>(); + list.add("baeldung"); + + assertFalse(list.containsAll(collection1)); + assertTrue(list.containsAll(collection2)); + } + + @Test + public void givenList_whenSet_thenOldElementIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + Object element = list.set(0, null); + + assertEquals("baeldung", element); + assertNull(list.get(0)); + } + + @Test + public void givenList_whenClear_thenAllElementsAreRemoved() { + List list = new CustomList<>(); + list.add("baeldung"); + list.clear(); + + assertTrue(list.isEmpty()); + } + + @Test + public void givenList_whenIndexOf_thenIndexZeroIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + + assertEquals(0, list.indexOf("baeldung")); + } + + @Test + public void givenList_whenIndexOf_thenPositiveIndexOrMinusOneIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add(".com"); + list.add(".com"); + + assertEquals(1, list.indexOf(".com")); + assertEquals(-1, list.indexOf("com")); + } + + @Test + public void whenLastIndexOf_thenIndexZeroIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + + assertEquals(0, list.lastIndexOf("baeldung")); + } + + @Test + public void whenLastIndexOf_thenPositiveIndexOrMinusOneIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add("baeldung"); + list.add(".com"); + + assertEquals(1, list.lastIndexOf("baeldung")); + assertEquals(-1, list.indexOf("com")); + } + + @Test + public void whenSubListZeroToOne_thenListContainingFirstElementIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + List subList = list.subList(0, 1); + + assertEquals("baeldung", subList.get(0)); + } + + @Test + public void whenSubListOneToTwo_thenListContainingSecondElementIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add("."); + list.add("com"); + List subList = list.subList(1, 2); + + assertEquals(1, subList.size()); + assertEquals(".", subList.get(0)); + } + + @Test + public void givenListWithElements_whenToArray_thenArrayContainsThose() { + List list = new CustomList<>(); + list.add("baeldung"); + list.add(".com"); + Object[] array = list.toArray(); + + assertArrayEquals(new Object[] { "baeldung", ".com" }, array); + } + + @Test + public void givenListWithAnElement_whenToArray_thenInputArrayIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + String[] input = new String[1]; + String[] output = list.toArray(input); + + assertArrayEquals(new String[] { "baeldung" }, input); + } + + @Test + public void whenToArrayIsCalledWithEmptyInputArray_thenNewArrayIsReturned() { + List list = new CustomList<>(); + list.add("baeldung"); + String[] input = {}; + String[] output = list.toArray(input); + + assertArrayEquals(new String[] { "baeldung" }, output); + } + + @Test + public void whenToArrayIsCalledWithLargerInput_thenOutputHasTrailingNull() { + List list = new CustomList<>(); + list.add("baeldung"); + String[] input = new String[2]; + String[] output = list.toArray(input); + + assertArrayEquals(new String[] { "baeldung", null }, output); + } + + @Test + public void givenListWithOneElement_whenIterator_thenThisElementIsNext() { + List list = new CustomList<>(); + list.add("baeldung"); + Iterator iterator = list.iterator(); + + assertTrue(iterator.hasNext()); + assertEquals("baeldung", iterator.next()); + } + + @Test + public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() { + List list = new CustomList<>(); + list.add("baeldung"); + Iterator iterator = list.iterator(); + + iterator.next(); + assertFalse(iterator.hasNext()); + } +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java new file mode 100644 index 0000000000..172a2fe417 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; +import java.util.List; +import java.util.ListIterator; + +import org.apache.commons.collections4.iterators.ReverseListIterator; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +public class ReverseIteratorUnitTest { + + private final ReverseIterator reverseIterator = new ReverseIterator(); + + private List list; + + private final String originalString = "ABCDE"; + + @BeforeEach + void setUp() { + + list = Lists.newArrayList("A", "B", "C", "D", "E"); + } + + @Test + void whenIteratingUsingForLoop_thenCorrect() { + + String reverseString = ""; + for (int i = list.size(); i-- > 0; ) { + reverseString += list.get(i); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingListIterator_thenCorrect() { + + String reverseString = ""; + final ListIterator listIterator = list.listIterator(list.size()); + while (listIterator.hasPrevious()) { + reverseString += listIterator.previous(); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingCollections_thenCorrect() { + + String reverseString = ""; + Collections.reverse(list); + for (final String item : list) { + reverseString += item; + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + + assertEquals("E", list.get(0)); + } + + @Test + void whenIteratingUsingApacheReverseListIterator_thenCorrect() { + + String reverseString = ""; + final ReverseListIterator listIterator = new ReverseListIterator(list); + while (listIterator.hasNext()) { + reverseString += listIterator.next(); + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + } + + @Test + void whenIteratingUsingGuava_thenCorrect() { + + String reverseString = ""; + final List reversedList = Lists.reverse(list); + for (final String item : reversedList) { + reverseString += item; + } + assertEquals(reverseString, StringUtils.reverse(originalString)); + + assertEquals("A", list.get(0)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java new file mode 100644 index 0000000000..5eb75f5cad --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.java8; + +import com.google.common.collect.Lists; +import org.junit.Test; + +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; + +public class Java8CollectionCleanupUnitTest { + + // tests - + + @Test + public void givenListContainsNulls_whenFilteringParallel_thenCorrect() { + final List list = Lists.newArrayList(null, 1, 2, null, 3, null); + final List listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList()); + + assertThat(listWithoutNulls, hasSize(3)); + } + + @Test + public void givenListContainsNulls_whenFilteringSerial_thenCorrect() { + final List list = Lists.newArrayList(null, 1, 2, null, 3, null); + final List listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList()); + + assertThat(listWithoutNulls, hasSize(3)); + } + + @Test + public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() { + final List listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null); + listWithoutNulls.removeIf(Objects::isNull); + + assertThat(listWithoutNulls, hasSize(3)); + } + + @Test + public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() { + final List listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0); + final List listWithoutDuplicates = listWithDuplicates.stream().distinct().collect(Collectors.toList()); + + assertThat(listWithoutDuplicates, hasSize(5)); + assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2)); + } + +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java new file mode 100644 index 0000000000..c2cc39c685 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.Car; +import com.baeldung.java_8_features.Person; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; + +public class Java8MaxMinUnitTest { + + @Test + public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() { + //given + final List listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10); + final Integer expectedResult = 89; + + //then + final Integer max = listOfIntegers + .stream() + .mapToInt(v -> v) + .max().orElseThrow(NoSuchElementException::new); + + assertEquals("Should be 89", expectedResult, max); + } + + @Test + public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() { + //given + final Person alex = new Person("Alex", 23); + final Person john = new Person("John", 40); + final Person peter = new Person("Peter", 32); + final List people = Arrays.asList(alex, john, peter); + + //then + final Person minByAge = people + .stream() + .min(Comparator.comparing(Person::getAge)) + .orElseThrow(NoSuchElementException::new); + + assertEquals("Should be Alex", alex, minByAge); + } + + @Test + public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() { + int[] integers = new int[] { 20, 98, 12, 7, 35 }; + + int min = Arrays.stream(integers) + .min() + .getAsInt(); + + assertEquals(7, min); + } + + @Test + public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() { + final Car porsche = new Car("Porsche 959", 319); + final Car ferrari = new Car("Ferrari 288 GTO", 303); + final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415); + final Car mcLaren = new Car("McLaren F1", 355); + final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren }; + + final Car maxBySpeed = Arrays.stream(fastCars) + .max(Comparator.comparing(Car::getTopSpeed)) + .orElseThrow(NoSuchElementException::new); + + assertEquals(bugatti, maxBySpeed); + } +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java new file mode 100644 index 0000000000..93c28812bd --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.list; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; + +public class AddElementsUnitTest { + + List flowers; + + @Before + public void init() { + this.flowers = new ArrayList<>(Arrays.asList( + new Flower("Poppy", 12), + new Flower("Anemone", 8), + new Flower("Catmint", 12))); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() { + List anotherList = new ArrayList<>(); + anotherList.addAll(flowers); + + Flower flower = anotherList.get(0); + flower.setPetals(flowers.get(0).getPetals() * 3); + + assertEquals(anotherList.size(), flowers.size()); + Assert.assertTrue(anotherList.containsAll(flowers)); + } + + @Test + public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() { + List target = new ArrayList<>(); + + Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0)); + + assertEquals(target.size(), 4); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .skip(1) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() { + List flowerVase = new ArrayList<>(); + + flowers.stream() + .filter(f -> f.getPetals() > 10) + .forEachOrdered(flowerVase::add); + + assertEquals(flowerVase.size() + 1, flowers.size()); + assertFalse(flowerVase.containsAll(flowers)); + } + + @Test + public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() { + List target = new ArrayList<>(); + + Optional.ofNullable(flowers) + .ifPresent(target::addAll); + + assertNotNull(target); + assertEquals(target.size(), 3); + } +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java new file mode 100644 index 0000000000..5327e5f4f0 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.list.listoflist; + +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class ListOfListsUnitTest { + + private List> listOfLists = new ArrayList<>(); + private List penList = new ArrayList<>(); + private List pencilList = new ArrayList<>(); + private List rubberList = new ArrayList<>(); + + @SuppressWarnings("unchecked") + @Before + public void init() { + listOfLists.add(penList); + listOfLists.add(pencilList); + listOfLists.add(rubberList); + + ((ArrayList) listOfLists.get(0)).add(new Pen("Pen 1")); + ((ArrayList) listOfLists.get(1)).add(new Pencil("Pencil 1")); + ((ArrayList) listOfLists.get(2)).add(new Rubber("Rubber 1")); + } + + @Test + public void givenListOfLists_thenCheckNames() { + assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName()); + } + + @SuppressWarnings("unchecked") + @Test + public void givenListOfLists_whenRemovingElements_thenCheckNames() { + + ((ArrayList) listOfLists.get(1)).remove(0); + listOfLists.remove(1); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName()); + listOfLists.remove(0); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName()); + } + + @Test + public void givenThreeList_whenCombineIntoOneList_thenCheckList() { + ArrayList pens = new ArrayList<>(); + pens.add(new Pen("Pen 1")); + pens.add(new Pen("Pen 2")); + ArrayList pencils = new ArrayList<>(); + pencils.add(new Pencil("Pencil 1")); + pencils.add(new Pencil("Pencil 2")); + ArrayList rubbers = new ArrayList<>(); + rubbers.add(new Rubber("Rubber 1")); + rubbers.add(new Rubber("Rubber 2")); + + List> list = new ArrayList>(); + list.add(pens); + list.add(pencils); + list.add(rubbers); + + assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName()); + } +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java new file mode 100644 index 0000000000..95e013b481 --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.list.random; + +import com.google.common.collect.Lists; +import org.junit.Test; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class RandomListElementUnitTest { + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { + List givenList = Lists.newArrayList(1, 2, 3); + Random rand = new Random(); + + givenList.get(rand.nextInt(givenList.size())); + } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { + List givenList = Lists.newArrayList(1, 2, 3); + + givenList.get((int) (Math.random() * givenList.size())); + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + } + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + givenList.remove(randomIndex); + } + } + + @Test + public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + Collections.shuffle(givenList); + + int randomSeriesLength = 3; + + givenList.subList(0, randomSeriesLength - 1); + } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size(); + + givenList.get(randomIndex); + } + +} diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java new file mode 100644 index 0000000000..c1a990342f --- /dev/null +++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java @@ -0,0 +1,212 @@ +package com.baeldung.list.removeall; + +import static com.baeldung.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies; +import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements; +import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList; +import static com.baeldung.list.removeall.RemoveAll.removeWithForEachLoop; +import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove; +import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains; +import static com.baeldung.list.removeall.RemoveAll.removeWithIterator; +import static com.baeldung.list.removeall.RemoveAll.removeWithRemoveIf; +import static com.baeldung.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex; +import static com.baeldung.list.removeall.RemoveAll.removeWithStreamFilter; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement; +import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopStoringFirstOccurrenceIndex; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class RemoveAllUnitTest { + + private List list(Integer... elements) { + return new ArrayList<>(Arrays.asList(elements)); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove)) + .isInstanceOf(IndexOutOfBoundsException.class); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithWhileLoopNonPrimitiveElement(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithCallingRemoveUntilModifies(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() { + // given + List list = list(1, 2, 3); + int valueToRemove = 1; + + // when + removeWithStandardForLoopUsingIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithStandardForLoopUsingIndex(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(1, 2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithForLoopDecrementOnRemove(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithForLoopIncrementIfRemains(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove)) + .isInstanceOf(ConcurrentModificationException.class); + } + + @Test + public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithIterator(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + List result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove); + + // then + assertThat(result).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + List result = removeWithStreamFilter(list, valueToRemove); + + // then + assertThat(result).isEqualTo(list(2, 3)); + } + + @Test + public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() { + // given + List list = list(1, 1, 2, 3); + int valueToRemove = 1; + + // when + removeWithRemoveIf(list, valueToRemove); + + // then + assertThat(list).isEqualTo(list(2, 3)); + } + +}