[BAEL-10836] - Create core-java-collections-list module

This commit is contained in:
amit2103
2018-12-23 01:15:24 +05:30
parent e0d24b6780
commit bba9a99f32
46 changed files with 93 additions and 25 deletions

View File

@@ -0,0 +1,28 @@
=========
## Core Java Collections List Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](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)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [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)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)

View File

@@ -0,0 +1,48 @@
<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>
<packaging>jar</packaging>
<name>core-java-collections-list</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</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>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<lombok.version>1.16.12</lombok.version>
</properties>
</project>

View File

@@ -0,0 +1,21 @@
package com.baeldung.classcastexception;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ClassCastException {
public static void main(String[] args) {
String p1 = new String("John");
String p2 = new String("Snow");
String[] strArray = new String[] { p1, p2 };
ArrayList<String> strList = (ArrayList<String>) Arrays.asList(strArray);
// To fix the ClassCastException at above line, modify the code as:
// List<String> strList = Arrays.asList(strArray);
System.out.println("String list: " + strList);
}
}

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

View File

@@ -0,0 +1,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,28 @@
package com.baeldung.java.list;
public class Flower {
private String name;
private int petals;
public Flower(String name, int petals) {
this.name = name;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPetals() {
return petals;
}
public void setPetals(int petals) {
this.petals = petals;
}
}

View File

@@ -0,0 +1,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,67 @@
package com.baeldung.java.list;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Demonstrates the different ways to loop over
* the elements of a list.
*/
public class WaysToIterate {
List<String> countries = Arrays.asList("Germany", "Panama", "Australia");
/**
* Iterate over a list using a basic for loop
*/
public void iterateWithForLoop() {
for (int i = 0; i < countries.size(); i++) {
System.out.println(countries.get(i));
}
}
/**
* Iterate over a list using the enhanced for loop
*/
public void iterateWithEnhancedForLoop() {
for (String country : countries) {
System.out.println(country);
}
}
/**
* Iterate over a list using an Iterator
*/
public void iterateWithIterator() {
Iterator<String> countriesIterator = countries.iterator();
while(countriesIterator.hasNext()) {
System.out.println(countriesIterator.next());
}
}
/**
* Iterate over a list using a ListIterator
*/
public void iterateWithListIterator() {
ListIterator<String> listIterator = countries.listIterator();
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
/**
* Iterate over a list using the Iterable.forEach() method
*/
public void iterateWithForEach() {
countries.forEach(System.out::println);
}
/**
* Iterate over a list using the Stream.forEach() method
*/
public void iterateWithStreamForEach() {
countries.stream().forEach((c) -> System.out.println(c));
}
}

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,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,37 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ArrayListOfArrayList {
public static void main(String args[]) {
int vertex = 5;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(vertex);
//Initializing each element of ArrayList with ArrayList
for(int i=0; i< vertex; i++) {
graph.add(new ArrayList<Integer>());
}
//We can add any number of columns to each row
graph.get(0).add(1);
graph.get(0).add(5);
graph.get(1).add(0);
graph.get(1).add(2);
graph.get(2).add(1);
graph.get(2).add(3);
graph.get(3).add(2);
graph.get(3).add(4);
graph.get(4).add(3);
graph.get(4).add(5);
//Printing all the edges
for(int i=0; i<vertex; i++) {
for(int j=0; j<graph.get(i).size(); j++) {
System.out.println("Edge between vertex "+i+"and "+graph.get(i).get(j));
}
}
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ThreeDimensionalArrayList {
public static void main(String args[]) {
int x_axis_length = 2;
int y_axis_length = 2;
int z_axis_length = 2;
ArrayList< ArrayList< ArrayList<String> > > space = new ArrayList<>(x_axis_length);
//Initializing each element of ArrayList with ArrayList< ArrayList<String> >
for(int i=0; i< x_axis_length; i++) {
space.add(new ArrayList< ArrayList<String> >(y_axis_length));
for(int j =0; j< y_axis_length; j++) {
space.get(i).add(new ArrayList<String>(z_axis_length));
}
}
//Set Red color for points (0,0,0) and (0,0,1)
space.get(0).get(0).add("Red");
space.get(0).get(0).add("Red");
//Set Blue color for points (0,1,0) and (0,1,1)
space.get(0).get(1).add("Blue");
space.get(0).get(1).add("Blue");
//Set Green color for points (1,0,0) and (1,0,1)
space.get(1).get(0).add("Green");
space.get(1).get(0).add("Green");
//Set Yellow color for points (1,1,0) and (1,1,1)
space.get(1).get(1).add("Yellow");
space.get(1).get(1).add("Yellow");
//Printing colors for all the points
for(int i=0; i<x_axis_length; i++) {
for(int j=0; j<y_axis_length; j++) {
for(int k=0; k<z_axis_length; k++) {
System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k));
}
}
}
}
}

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,116 @@
package com.baeldung.array.converter;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class ArrayConvertToListUnitTest {
@Test
public void givenAnStringArray_whenConvertArrayToList_thenListCreated() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
}
@Test
public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() {
int[] primitives = { 1, 2, 3, 4 };
List numbers = Arrays.asList(primitives);
assertNotNull(numbers);
assertEquals(numbers.size(), 1);
assertEquals(numbers.get(0), primitives);
}
@Test(expected = UnsupportedOperationException.class)
public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.add("Celosia");
}
@Test(expected = UnsupportedOperationException.class)
public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.remove("Poppy");
}
@Test
public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
List<String> newflowerList = new ArrayList<>(flowerList);
assertNotNull(newflowerList);
assertEquals(newflowerList.size(), 4);
assertEquals(newflowerList.get(0), "Ageratum");
assertEquals(newflowerList.get(1), "Allium");
assertEquals(newflowerList.get(2), "Poppy");
assertEquals(newflowerList.get(3), "Catmint");
newflowerList.add("Celosia");
assertEquals(newflowerList.size(), 5);
assertEquals(newflowerList.get(4), "Celosia");
}
@Test
public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = new ArrayList<>();
for(String flower: flowers) {
flowerList.add(flower);
}
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.add("Celosia");
assertEquals(flowerList.size(), 5);
assertEquals(flowerList.get(4), "Celosia");
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.collection;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests demonstrating differences between ArrayList#clear() and ArrayList#removeAll()
*/
class ClearVsRemoveAllUnitTest {
/*
* Tests
*/
@Test
void givenArrayListWithElements_whenClear_thenListBecomesEmpty() {
Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
collection.clear();
assertTrue(collection.isEmpty());
}
@Test
void givenTwoArrayListsWithCommonElements_whenRemoveAll_thenFirstListMissElementsFromSecondList() {
Collection<Integer> firstCollection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collection<Integer> secondCollection = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7));
firstCollection.removeAll(secondCollection);
assertEquals(Arrays.asList(1, 2), firstCollection);
assertEquals(Arrays.asList(3, 4, 5, 6, 7), secondCollection);
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Test;
public class CollectionsEmpty {
@Test
public void givenArrayList_whenAddingElement_addsNewElement() {
ArrayList<String> mutableList = new ArrayList<>();
mutableList.add("test");
Assert.assertEquals(mutableList.size(), 1);
Assert.assertEquals(mutableList.get(0), "test");
}
@Test(expected = UnsupportedOperationException.class)
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
List<String> immutableList = Collections.emptyList();
immutableList.add("test");
}
}

View File

@@ -0,0 +1,89 @@
package com.baeldung.findItems;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class FindItemsBasedOnOtherStreamUnitTest {
private List<Employee> employeeList = new ArrayList<Employee>();
private List<Department> departmentList = new ArrayList<Department>();
@Test
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
Integer expectedId = 1002;
populate(employeeList, departmentList);
List<Employee> filteredList = employeeList.stream()
.filter(empl -> departmentList.stream()
.anyMatch(dept -> dept.getDepartment()
.equals("sales") && empl.getEmployeeId()
.equals(dept.getEmployeeId())))
.collect(Collectors.toList());
assertEquals(expectedId, filteredList.get(0)
.getEmployeeId());
}
private void populate(List<Employee> EmplList, List<Department> deptList) {
Employee employee1 = new Employee(1001, "empl1");
Employee employee2 = new Employee(1002, "empl2");
Employee employee3 = new Employee(1003, "empl3");
Collections.addAll(EmplList, employee1, employee2, employee3);
Department department1 = new Department(1002, "sales");
Department department2 = new Department(1003, "marketing");
Department department3 = new Department(1004, "sales");
Collections.addAll(deptList, department1, department2, department3);
}
}
class Employee {
private Integer employeeId;
private String employeeName;
Employee(Integer employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
Integer getEmployeeId() {
return employeeId;
}
public String getEmployeeName() {
return employeeName;
}
}
class Department {
private Integer employeeId;
private String department;
Department(Integer employeeId, String department) {
super();
this.employeeId = employeeId;
this.department = department;
}
Integer getEmployeeId() {
return employeeId;
}
String getDepartment() {
return department;
}
}

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,133 @@
package com.baeldung.java.list;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class CopyListServiceUnitTest {
List<Flower> flowers;
private CopyListService copyListService;
@Before
public void init() {
this.copyListService = new CopyListService();
this.flowers = new ArrayList<>();
Flower poppy = new Flower("Poppy", 12);
flowers.add(poppy);
Flower anemone = new Flower("Anemone", 8);
flowers.add(anemone);
Flower catmint = new Flower("Catmint", 12);
flowers.add(catmint);
Flower diascia = new Flower("Diascia", 5);
flowers.add(diascia);
Flower iris = new Flower("Iris", 3);
flowers.add(iris);
Flower pansy = new Flower("Pansy", 5);
flowers.add(pansy);
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() {
List<Flower> copy = copyListService.copyListByConstructor(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() {
List<Flower> copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethod(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() {
List<Flower> copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> dest = Arrays.asList(4,5,6);
dest = copyListService.copyListByCopyMethod(source, dest);
assertEquals(dest.size(), source.size());
assertTrue(dest.containsAll(source));
}
@Test
public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> dest = Arrays.asList(5,6,7,8,9,10);
dest = copyListService.copyListByCopyMethod(source, dest);
assertNotEquals(dest.size(), source.size());
assertTrue(dest.containsAll(source));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStream(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamAndSkipFirstElement(flowers);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 1, flowers.size());
assertFalse(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithFilter(flowers, 5);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 3, flowers.size());
assertFalse(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptional(null);
assertNotNull(copy);
assertEquals(copy.size(), 0);
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptional(flowers);
assertEquals(copy.size(), flowers.size());
assertTrue(copy.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() {
List<Flower> copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers);
assertNotEquals(copy.size(), flowers.size());
assertEquals(copy.size() + 1, flowers.size());
assertFalse(copy.containsAll(flowers));
}
}

View File

@@ -0,0 +1,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,71 @@
package com.baeldung.java.list;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.junit.Test;
public class WaysToIterateUnitTest {
List<String> globalCountries = new ArrayList<String>();
List<String> europeanCountries = Arrays.asList("Germany", "Panama", "Australia");
@Test
public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() {
for (int i = 0; i < europeanCountries.size(); i++) {
globalCountries.add(europeanCountries.get(i));
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() {
for (String country : europeanCountries) {
globalCountries.add(country);
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() {
Iterator<String> countriesIterator = europeanCountries.iterator();
while (countriesIterator.hasNext()) {
globalCountries.add(countriesIterator.next());
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() {
ListIterator<String> countriesIterator = europeanCountries.listIterator();
while (countriesIterator.hasNext()) {
globalCountries.add(countriesIterator.next());
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() {
europeanCountries.forEach(country -> globalCountries.add(country));
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() {
europeanCountries.stream().forEach((country) -> globalCountries.add(country));
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.java.listInitialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
import org.junit.Test;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
Assert.assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
Assert.assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArrayAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
Assert.assertEquals("baz", list.get(0));
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
Assert.assertTrue(list.contains("foo"));
}
}

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,50 @@
package com.baeldung.list.flattennestedlist;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListUnitTest {
private List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenNestedList_thenFlattenImperatively() {
List<String> ls = flattenListOfListsImperatively(lol);
assertNotNull(ls);
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
@Test
public void givenNestedList_thenFlattenFunctionally() {
List<String> ls = flattenListOfListsStream(lol);
assertNotNull(ls);
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
private <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,69 @@
package com.baeldung.list.listoflist;
import com.baeldung.java.list.Flower;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class AddElementsToListUnitTest {
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,210 @@
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.Test;
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));
}
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.list.removefirst;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class RemoveFirstElementUnitTest {
private List<String> list = new ArrayList<>();
private LinkedList<String> linkedList = new LinkedList<>();
@Before
public void init() {
list.add("cat");
list.add("dog");
list.add("pig");
list.add("cow");
list.add("goat");
linkedList.add("cat");
linkedList.add("dog");
linkedList.add("pig");
linkedList.add("cow");
linkedList.add("goat");
}
@Test
public void givenList_whenRemoveFirst_thenRemoved() {
list.remove(0);
assertThat(list, hasSize(4));
assertThat(list, not(contains("cat")));
}
@Test
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
linkedList.removeFirst();
assertThat(linkedList, hasSize(4));
assertThat(linkedList, not(contains("cat")));
}
@Test
public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
assertThat(modifiedArray.length, is(2));
assertThat(modifiedArray[0], is("bar"));
}
}

View File

@@ -0,0 +1,71 @@
package org.baeldung;
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,137 @@
package org.baeldung.java.collections;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.*;
public class ArrayListUnitTest {
private List<String> stringsToSearch;
@Before
public void setUp() {
List<String> list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new));
stringsToSearch = new ArrayList<>(list);
stringsToSearch.addAll(list);
}
@Test
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());
}
@Test
public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
Collection<Integer> numbers = IntStream.range(0, 10).boxed().collect(toSet());
List<Integer> list = new ArrayList<>(numbers);
assertEquals(10, list.size());
assertTrue(numbers.containsAll(list));
}
@Test
public void givenElement_whenAddToArrayList_thenIsAdded() {
List<Long> list = new ArrayList<>();
list.add(1L);
list.add(2L);
list.add(1, 3L);
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
}
@Test
public void givenCollection_whenAddToArrayList_thenIsAdded() {
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
}
@Test
public void givenExistingElement_whenCallIndexOf_thenReturnCorrectIndex() {
assertEquals(10, stringsToSearch.indexOf("a"));
assertEquals(26, stringsToSearch.lastIndexOf("a"));
}
@Test
public void givenCondition_whenIterateArrayList_thenFindAllElementsSatisfyingCondition() {
Iterator<String> it = stringsToSearch.iterator();
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
List<String> result = new ArrayList<>();
while (it.hasNext()) {
String s = it.next();
if (matchingStrings.contains(s)) {
result.add(s);
}
}
assertEquals(6, result.size());
}
@Test
public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() {
Set<String> matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
List<String> result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new));
assertEquals(6, result.size());
}
@Test
public void givenSortedArray_whenUseBinarySearch_thenFindElement() {
List<String> copy = new ArrayList<>(stringsToSearch);
Collections.sort(copy);
int index = Collections.binarySearch(copy, "f");
assertThat(index, not(equalTo(-1)));
}
@Test
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(list);
list.remove(0);
assertThat(list.get(0), equalTo(8));
list.remove(Integer.valueOf(0));
assertFalse(list.contains(0));
}
@Test
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = list.listIterator(list.size());
List<Integer> result = new ArrayList<>(list.size());
while (it.hasPrevious()) {
result.add(it.previous());
}
Collections.reverse(list);
assertThat(result, equalTo(list));
}
@Test
public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
Set<String> matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f");
Iterator<String> it = stringsToSearch.iterator();
while (it.hasNext()) {
if (matchingStrings.contains(it.next())) {
it.remove();
}
}
assertEquals(20, stringsToSearch.size());
}
}

View File

@@ -0,0 +1,56 @@
package org.baeldung.java.collections;
import com.google.common.collect.ImmutableList;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CoreJavaCollectionsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class);
// tests -
@Test
public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> synchronizedList = Collections.synchronizedList(list);
LOG.debug("Synchronized List is: " + synchronizedList);
}
@Test(expected = UnsupportedOperationException.class)
public final void givenUsingTheJdk_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> unmodifiableList = Collections.unmodifiableList(list);
unmodifiableList.add("four");
}
@Test(expected = UnsupportedOperationException.class)
public final void givenUsingGuava_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> unmodifiableList = ImmutableList.copyOf(list);
unmodifiableList.add("four");
}
@Test(expected = UnsupportedOperationException.class)
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build();
unmodifiableList.add("four");
}
@Test(expected = UnsupportedOperationException.class)
public final void givenUsingCommonsCollections_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final List<String> unmodifiableList = ListUtils.unmodifiableList(list);
unmodifiableList.add("four");
}
}

View File

@@ -0,0 +1,83 @@
package org.baeldung.java.collections;
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.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 final void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null);
while (list.remove(null))
;
assertThat(list, hasSize(1));
}
@Test
public final void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null);
list.removeAll(Collections.singleton(null));
assertThat(list, hasSize(1));
}
@Test
public final void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
final List<Integer> list = Lists.newArrayList(null, 1, null);
Iterables.removeIf(list, Predicates.isNull());
assertThat(list, hasSize(1));
}
@Test
public final 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 final 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 final void givenListContainsDuplicates_whenRemovingDuplicatesWithPlainJava_thenCorrect() {
final List<Integer> listWithDuplicates = Lists.newArrayList(0, 1, 2, 3, 0, 0);
final List<Integer> listWithoutDuplicates = new ArrayList<>(new HashSet<>(listWithDuplicates));
assertThat(listWithoutDuplicates, hasSize(4));
}
@Test
public final void givenListContainsDuplicates_whenRemovingDuplicatesWithGuava_thenCorrect() {
final List<Integer> listWithDuplicates = Lists.newArrayList(0, 1, 2, 3, 0, 0);
final List<Integer> listWithoutDuplicates = Lists.newArrayList(Sets.newHashSet(listWithDuplicates));
assertThat(listWithoutDuplicates, hasSize(4));
}
}

View File

@@ -0,0 +1,23 @@
package org.baeldung.java.lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ListAssertJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
assertThat(list1).isEqualTo(list2).isNotEqualTo(list3);
assertThat(list1.equals(list2)).isTrue();
assertThat(list1.equals(list3)).isFalse();
}
}

View File

@@ -0,0 +1,47 @@
package org.baeldung.java.lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ListJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2);
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
}
@Test
public void whenIntersection_ShouldReturnCommonElements() throws Exception {
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Set<String> commonElements = new HashSet(Arrays.asList("red", "green"));
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, result);
Set<String> inverseResult = otherList.stream()
.distinct()
.filter(list::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, inverseResult);
}
}

View File

@@ -0,0 +1,22 @@
package org.baeldung.java.lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class ListTestNgUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
assertEquals(list1, list2);
assertNotSame(list1, list2);
assertNotEquals(list1, list3);
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)