[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

@@ -1,116 +0,0 @@
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

@@ -1,40 +0,0 @@
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

@@ -1,26 +0,0 @@
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

@@ -1,89 +0,0 @@
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

@@ -1,158 +0,0 @@
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

@@ -1,133 +0,0 @@
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

@@ -1,296 +0,0 @@
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

@@ -1,87 +0,0 @@
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

@@ -1,71 +0,0 @@
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

@@ -1,59 +0,0 @@
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

@@ -1,74 +0,0 @@
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

@@ -1,50 +0,0 @@
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

@@ -1,69 +0,0 @@
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

@@ -1,69 +0,0 @@
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

@@ -1,210 +0,0 @@
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

@@ -1,62 +0,0 @@
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

@@ -1,137 +0,0 @@
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

@@ -1,56 +0,0 @@
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

@@ -1,83 +0,0 @@
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

@@ -1,23 +0,0 @@
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

@@ -1,47 +0,0 @@
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

@@ -1,22 +0,0 @@
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

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