针对 Java List 相关的一些操作进行说明和示例

This commit is contained in:
YuCheng Hu 2022-04-15 14:55:42 -04:00
parent a838d6eb01
commit 9ca97e9cd5
25 changed files with 1929 additions and 0 deletions

View File

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

View File

@ -0,0 +1,31 @@
<?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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath></relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

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

View File

@ -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<Customer> customers) {
if (indexOfCustomer >= 0 && indexOfCustomer < customers.size())
return customers.get(indexOfCustomer);
return null;
}
public int findUsingIndexOf(Customer customer, List<Customer> customers) {
return customers.indexOf(customer);
}
public boolean findUsingContains(Customer customer, List<Customer> customers) {
return customers.contains(customer);
}
public Customer findUsingIterator(String name, List<Customer> customers) {
Iterator<Customer> 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<Customer> customers) {
for (Customer customer : customers) {
if (customer.getName().equals(name)) {
return customer;
}
}
return null;
}
public Customer findUsingStream(String name, List<Customer> customers) {
return customers.stream()
.filter(customer -> customer.getName().equals(name))
.findFirst()
.orElse(null);
}
public Customer findUsingParallelStream(String name, List<Customer> customers) {
return customers.parallelStream()
.filter(customer -> customer.getName().equals(name))
.findAny()
.orElse(null);
}
public Customer findUsingGuava(String name, List<Customer> customers) {
return Iterables.tryFind(customers, new Predicate<Customer>() {
public boolean apply(Customer customer) {
return customer.getName().equals(name);
}
}).orNull();
}
public Customer findUsingApacheCommon(String name, List<Customer> customers) {
return IterableUtils.find(customers, new org.apache.commons.collections4.Predicate<Customer>() {
public boolean evaluate(Customer customer) {
return customer.getName().equals(name);
}
});
}
}

View File

@ -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<E> implements List<E> {
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<? extends E> collection) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends E> 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<E> subList(int fromIndex, int toIndex) {
Object[] temp = new Object[toIndex - fromIndex];
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
return (List<E>) Arrays.asList(temp);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(internal, internal.length);
}
@SuppressWarnings("unchecked")
@Override
public <T> 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<E> iterator() {
return new CustomIterator();
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
// ignored for brevity
return null;
}
private class CustomIterator implements Iterator<E> {
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;
}
}
}

View File

@ -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<String> 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<String> 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<String> 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<String> 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<String> list) {
final List<String> reversedList = Lists.reverse(list);
for (final String item : reversedList) {
System.out.println(item);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,5 @@
package com.baeldung.list.listoflist;
public interface Stationery {
}

View File

@ -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<Integer> list, int element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopNonPrimitiveElement(List<Integer> list, Integer element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopStoringFirstOccurrenceIndex(List<Integer> list, Integer element) {
int index;
while ((index = list.indexOf(element)) >= 0) {
list.remove(index);
}
}
static void removeWithCallingRemoveUntilModifies(List<Integer> list, Integer element) {
while (list.remove(element))
;
}
static void removeWithStandardForLoopUsingIndex(List<Integer> 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<Integer> 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<Integer> 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<Integer> list, int element) {
for (Integer number : list) {
if (Objects.equals(number, element)) {
list.remove(number);
}
}
}
static void removeWithIterator(List<Integer> list, int element) {
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
Integer number = i.next();
if (Objects.equals(number, element)) {
i.remove();
}
}
}
static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
return remainingElements;
}
static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
list.clear();
list.addAll(remainingElements);
}
static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) {
return list.stream()
.filter(e -> !Objects.equals(e, element))
.collect(Collectors.toList());
}
static void removeWithRemoveIf(List<Integer> list, Integer element) {
list.removeIf(n -> Objects.equals(n, element));
}
}

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,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<Integer> list = Lists.newArrayList(null, 1, null);
while (list.remove(null))
;
assertThat(list, hasSize(1));
}
@Test
public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null);
list.removeAll(Collections.singleton(null));
assertThat(list, hasSize(1));
}
@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null);
Iterables.removeIf(list, Predicates.isNull());
assertThat(list, hasSize(1));
}
@Test
public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3);
final List<Integer> listWithoutNulls = Lists.newArrayList(Iterables.filter(list, Predicates.notNull()));
assertThat(listWithoutNulls, hasSize(3));
}
@Test
public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
final List<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
final List<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
final List<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
final List<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
final List<Integer> listWithoutDuplicates = Lists.newArrayList(Sets.newLinkedHashSet(listWithDuplicates));
assertThat(listWithoutDuplicates, hasSize(5));
assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2));
}
}

View File

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

View File

@ -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<Object> list = new CustomList<>();
assertTrue(list.isEmpty());
}
@Test
public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() {
List<Object> list = new CustomList<>();
list.add(null);
assertFalse(list.isEmpty());
}
@Test
public void givenListWithAnElement_whenSize_thenOneIsReturned() {
List<Object> list = new CustomList<>();
list.add(null);
assertEquals(1, list.size());
}
@Test
public void givenListWithAnElement_whenGet_thenThatElementIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
Object element = list.get(0);
assertEquals("baeldung", element);
}
@Test
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
List<Object> list = new CustomList<>();
boolean succeeded = list.add(null);
assertTrue(succeeded);
}
@Test
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
List<Object> 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<Object> collection = new ArrayList<>();
List<Object> list = new CustomList<>();
list.addAll(collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenAddAllToSpecifiedIndex_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
List<Object> list = new CustomList<>();
list.addAll(0, collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveAtSpecifiedIndex_thenExceptionIsThrown() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.remove(0);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveSpecifiedElement_thenExceptionIsThrown() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.remove("baeldung");
}
@Test(expected = UnsupportedOperationException.class)
public void whenRemoveAll_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.removeAll(collection);
}
@Test(expected = UnsupportedOperationException.class)
public void whenRetainAll_thenExceptionIsThrown() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
list.retainAll(collection);
}
@Test
public void givenEmptyList_whenContains_thenFalseIsReturned() {
List<Object> list = new CustomList<>();
assertFalse(list.contains(null));
}
@Test
public void givenListWithAnElement_whenContains_thenTrueIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
assertTrue(list.contains("baeldung"));
}
@Test
public void givenListWithAnElement_whenContainsAll_thenTrueIsReturned() {
Collection<Object> collection = new ArrayList<>();
collection.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
assertTrue(list.containsAll(collection));
}
@Test
public void givenList_whenContainsAll_thenEitherTrueOrFalseIsReturned() {
Collection<Object> collection1 = new ArrayList<>();
collection1.add("baeldung");
collection1.add(".com");
Collection<Object> collection2 = new ArrayList<>();
collection2.add("baeldung");
List<Object> list = new CustomList<>();
list.add("baeldung");
assertFalse(list.containsAll(collection1));
assertTrue(list.containsAll(collection2));
}
@Test
public void givenList_whenSet_thenOldElementIsReturned() {
List<Object> 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<Object> list = new CustomList<>();
list.add("baeldung");
list.clear();
assertTrue(list.isEmpty());
}
@Test
public void givenList_whenIndexOf_thenIndexZeroIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
assertEquals(0, list.indexOf("baeldung"));
}
@Test
public void givenList_whenIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
List<Object> 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<Object> list = new CustomList<>();
list.add("baeldung");
assertEquals(0, list.lastIndexOf("baeldung"));
}
@Test
public void whenLastIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
List<Object> 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<Object> list = new CustomList<>();
list.add("baeldung");
List<Object> subList = list.subList(0, 1);
assertEquals("baeldung", subList.get(0));
}
@Test
public void whenSubListOneToTwo_thenListContainingSecondElementIsReturned() {
List<Object> list = new CustomList<>();
list.add("baeldung");
list.add(".");
list.add("com");
List<Object> subList = list.subList(1, 2);
assertEquals(1, subList.size());
assertEquals(".", subList.get(0));
}
@Test
public void givenListWithElements_whenToArray_thenArrayContainsThose() {
List<Object> 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<Object> 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<Object> list = new CustomList<>();
list.add("baeldung");
String[] input = {};
String[] output = list.toArray(input);
assertArrayEquals(new String[] { "baeldung" }, output);
}
@Test
public void whenToArrayIsCalledWithLargerInput_thenOutputHasTrailingNull() {
List<Object> 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<Object> list = new CustomList<>();
list.add("baeldung");
Iterator<Object> iterator = list.iterator();
assertTrue(iterator.hasNext());
assertEquals("baeldung", iterator.next());
}
@Test
public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() {
List<Object> list = new CustomList<>();
list.add("baeldung");
Iterator<Object> iterator = list.iterator();
iterator.next();
assertFalse(iterator.hasNext());
}
}

View File

@ -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<String> 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<String> reversedList = Lists.reverse(list);
for (final String item : reversedList) {
reverseString += item;
}
assertEquals(reverseString, StringUtils.reverse(originalString));
assertEquals("A", list.get(0));
}
}

View File

@ -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<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3));
}
@Test
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
assertThat(listWithoutNulls, hasSize(3));
}
@Test
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
final List<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
final List<Integer> listWithoutDuplicates = listWithDuplicates.stream().distinct().collect(Collectors.toList());
assertThat(listWithoutDuplicates, hasSize(5));
assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2));
}
}

View File

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

View File

@ -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<Flower> 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<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
List<Flower> 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<Flower> 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<Flower> 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<Flower> 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<Flower> target = new ArrayList<>();
Optional.ofNullable(flowers)
.ifPresent(target::addAll);
assertNotNull(target);
assertEquals(target.size(), 3);
}
}

View File

@ -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<List<? extends Stationery>> listOfLists = new ArrayList<>();
private List<Pen> penList = new ArrayList<>();
private List<Pencil> pencilList = new ArrayList<>();
private List<Rubber> rubberList = new ArrayList<>();
@SuppressWarnings("unchecked")
@Before
public void init() {
listOfLists.add(penList);
listOfLists.add(pencilList);
listOfLists.add(rubberList);
((ArrayList<Pen>) listOfLists.get(0)).add(new Pen("Pen 1"));
((ArrayList<Pencil>) listOfLists.get(1)).add(new Pencil("Pencil 1"));
((ArrayList<Rubber>) 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<Pencil>) 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<Pen> pens = new ArrayList<>();
pens.add(new Pen("Pen 1"));
pens.add(new Pen("Pen 2"));
ArrayList<Pencil> pencils = new ArrayList<>();
pencils.add(new Pencil("Pencil 1"));
pencils.add(new Pencil("Pencil 2"));
ArrayList<Rubber> rubbers = new ArrayList<>();
rubbers.add(new Rubber("Rubber 1"));
rubbers.add(new Rubber("Rubber 2"));
List<ArrayList<? extends Stationery>> list = new ArrayList<ArrayList<? extends Stationery>>();
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());
}
}

View File

@ -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<Integer> givenList = Lists.newArrayList(1, 2, 3);
Random rand = new Random();
givenList.get(rand.nextInt(givenList.size()));
}
@Test
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
givenList.get((int) (Math.random() * givenList.size()));
}
@Test
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
Random rand = new Random();
List<String> 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<String> 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<Integer> 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<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size();
givenList.get(randomIndex);
}
}

View File

@ -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<Integer> list(Integer... elements) {
return new ArrayList<>(Arrays.asList(elements));
}
@Test
public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() {
// given
List<Integer> list = list(1, 2, 3);
int valueToRemove = 1;
// when
assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove))
.isInstanceOf(IndexOutOfBoundsException.class);
}
@Test
public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() {
// given
List<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> 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<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
List<Integer> result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove);
// then
assertThat(result).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() {
// given
List<Integer> 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<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
List<Integer> result = removeWithStreamFilter(list, valueToRemove);
// then
assertThat(result).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithRemoveIf(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
}