[Bael 6056] - Move collection-related logic from core-java to core-java-collections (#4114)
* Added parent module on poms that have no parent defined * Removed dependency reduced pom from undertow module * [BAEL-6056] - Move collection-related logic from core-java to core-java-collections * [BAEL-6056] - Move collection-related logic from core-java to core-java-collections * [BAEL-6056] - Move collection-related logic from core-java to core-java-collections * [BAEL-6056] - Move collection-related logic from core-java to core-java-collections
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
12cdd5357d
commit
cfd98d2fe3
@@ -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 ArrayConvertToListTest {
|
||||
|
||||
@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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.arraydeque;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArrayDequeTest {
|
||||
|
||||
@Test
|
||||
public void whenOffer_addsAtLast() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.offer("first");
|
||||
deque.offer("second");
|
||||
|
||||
assertEquals("second", deque.getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPoll_removesFirst() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.offer("first");
|
||||
deque.offer("second");
|
||||
|
||||
assertEquals("first", deque.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPush_addsAtFirst() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.push("first");
|
||||
deque.push("second");
|
||||
|
||||
assertEquals("second", deque.getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPop_removesLast() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.push("first");
|
||||
deque.push("second");
|
||||
|
||||
assertEquals("second", deque.pop());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenComparingTreeMapVsHashMap {
|
||||
|
||||
@Test
|
||||
public void whenInsertObjectsTreeMap_thenNaturalOrder() {
|
||||
Map<Integer, String> treemap = new TreeMap<>();
|
||||
treemap.put(3, "TreeMap");
|
||||
treemap.put(2, "vs");
|
||||
treemap.put(1, "HashMap");
|
||||
Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenInsertNullInTreeMap_thenException() {
|
||||
Map<Integer, String> treemap = new TreeMap<>();
|
||||
treemap.put(null, "NullPointerException");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertObjectsHashMap_thenRandomOrder() {
|
||||
Map<Integer, String> hashmap = new HashMap<>();
|
||||
hashmap.put(3, "TreeMap");
|
||||
hashmap.put(2, "vs");
|
||||
hashmap.put(1, "HashMap");
|
||||
Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertNullInHashMap_thenInsertsNull() {
|
||||
Map<Integer, String> hashmap = new HashMap<>();
|
||||
hashmap.put(null, null);
|
||||
Assert.assertNull(hashmap.get(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() {
|
||||
Map<Integer, String> treeMap = new HashMap<>();
|
||||
treeMap.put(1, "Baeldung");
|
||||
treeMap.put(1, "Baeldung");
|
||||
|
||||
Assert.assertTrue(treeMap.size() == 1);
|
||||
|
||||
Map<Integer, String> treeMap2 = new TreeMap<>();
|
||||
treeMap2.put(1, "Baeldung");
|
||||
treeMap2.put(1, "Baeldung");
|
||||
|
||||
Assert.assertTrue(treeMap2.size() == 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenUsingHashSet {
|
||||
|
||||
@Test
|
||||
public void whenAddingElement_shouldAddElement() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
Assert.assertTrue(hashset.add("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_shouldSearchForElement() {
|
||||
Set<String> hashsetContains = new HashSet<>();
|
||||
hashsetContains.add("String Added");
|
||||
Assert.assertTrue(hashsetContains.contains("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
|
||||
Set<String> hashSetSize = new HashSet<>();
|
||||
hashSetSize.add("String Added");
|
||||
Assert.assertEquals(1, hashSetSize.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
|
||||
Set<String> emptyHashSet = new HashSet<>();
|
||||
Assert.assertTrue(emptyHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElement_shouldRemoveElement() {
|
||||
Set<String> removeFromHashSet = new HashSet<>();
|
||||
removeFromHashSet.add("String Added");
|
||||
Assert.assertTrue(removeFromHashSet.remove("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClearingHashSet_shouldClearHashSet() {
|
||||
Set<String> clearHashSet = new HashSet<>();
|
||||
clearHashSet.add("String Added");
|
||||
clearHashSet.clear();
|
||||
Assert.assertTrue(clearHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingHashSet_shouldIterateHashSet() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
System.out.println(itr.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenModifyingHashSetWhileIterating_shouldThrowException() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
itr.next();
|
||||
hashset.remove("Second");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
String element = itr.next();
|
||||
if (element.equals("Second"))
|
||||
itr.remove();
|
||||
}
|
||||
Assert.assertEquals(2, hashset.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.baeldung.collection;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Iterator;
|
||||
import java.util.NavigableSet;
|
||||
import java.util.Set;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenUsingTreeSet {
|
||||
|
||||
private static class Element {
|
||||
private Integer id;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return id.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private Comparator<Element> comparator = (ele1, ele2) -> {
|
||||
return ele1.getId()
|
||||
.compareTo(ele2.getId());
|
||||
};
|
||||
|
||||
@Test
|
||||
public void whenAddingElement_shouldAddElement() {
|
||||
Set<String> treeSet = new TreeSet<>();
|
||||
Assert.assertTrue(treeSet.add("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_shouldSearchForElement() {
|
||||
Set<String> treeSetContains = new TreeSet<>();
|
||||
treeSetContains.add("String Added");
|
||||
Assert.assertTrue(treeSetContains.contains("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElement_shouldRemoveElement() {
|
||||
Set<String> removeFromTreeSet = new TreeSet<>();
|
||||
removeFromTreeSet.add("String Added");
|
||||
Assert.assertTrue(removeFromTreeSet.remove("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClearingTreeSet_shouldClearTreeSet() {
|
||||
Set<String> clearTreeSet = new TreeSet<>();
|
||||
clearTreeSet.add("String Added");
|
||||
clearTreeSet.clear();
|
||||
Assert.assertTrue(clearTreeSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() {
|
||||
Set<String> treeSetSize = new TreeSet<>();
|
||||
treeSetSize.add("String Added");
|
||||
Assert.assertEquals(1, treeSetSize.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() {
|
||||
Set<String> emptyTreeSet = new TreeSet<>();
|
||||
Assert.assertTrue(emptyTreeSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() {
|
||||
Set<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add("Second");
|
||||
treeSet.add("Third");
|
||||
Iterator<String> itr = treeSet.iterator();
|
||||
while (itr.hasNext()) {
|
||||
System.out.println(itr.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() {
|
||||
TreeSet<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add("Second");
|
||||
treeSet.add("Third");
|
||||
Iterator<String> itr = treeSet.descendingIterator();
|
||||
while (itr.hasNext()) {
|
||||
System.out.println(itr.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenModifyingTreeSetWhileIterating_shouldThrowException() {
|
||||
Set<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add("Second");
|
||||
treeSet.add("Third");
|
||||
Iterator<String> itr = treeSet.iterator();
|
||||
while (itr.hasNext()) {
|
||||
itr.next();
|
||||
treeSet.remove("Second");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
|
||||
Set<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add("Second");
|
||||
treeSet.add("Third");
|
||||
Iterator<String> itr = treeSet.iterator();
|
||||
while (itr.hasNext()) {
|
||||
String element = itr.next();
|
||||
if (element.equals("Second"))
|
||||
itr.remove();
|
||||
}
|
||||
Assert.assertEquals(2, treeSet.size());
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() {
|
||||
Set<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingFirstElement_shouldReturnFirstElement() {
|
||||
TreeSet<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
Assert.assertEquals("First", treeSet.first());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingLastElement_shouldReturnLastElement() {
|
||||
TreeSet<String> treeSet = new TreeSet<>();
|
||||
treeSet.add("First");
|
||||
treeSet.add("Last");
|
||||
Assert.assertEquals("Last", treeSet.last());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingComparator_shouldSortAndInsertElements() {
|
||||
Set<Element> treeSet = new TreeSet<>(comparator);
|
||||
Element ele1 = new Element();
|
||||
ele1.setId(100);
|
||||
Element ele2 = new Element();
|
||||
ele2.setId(200);
|
||||
|
||||
treeSet.add(ele1);
|
||||
treeSet.add(ele2);
|
||||
|
||||
System.out.println(treeSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHeadSet_shouldReturnElementsLessThanSpecifiedElement() {
|
||||
Set<Element> treeSet = new TreeSet<>(comparator);
|
||||
Element ele1 = new Element();
|
||||
ele1.setId(100);
|
||||
Element ele2 = new Element();
|
||||
ele2.setId(200);
|
||||
|
||||
treeSet.add(ele1);
|
||||
treeSet.add(ele2);
|
||||
|
||||
System.out.println(treeSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubSet_shouldReturnSubSetElements() {
|
||||
SortedSet<Integer> treeSet = new TreeSet<>();
|
||||
treeSet.add(1);
|
||||
treeSet.add(2);
|
||||
treeSet.add(3);
|
||||
treeSet.add(4);
|
||||
treeSet.add(5);
|
||||
treeSet.add(6);
|
||||
|
||||
Set<Integer> expectedSet = new TreeSet<>();
|
||||
expectedSet.add(2);
|
||||
expectedSet.add(3);
|
||||
expectedSet.add(4);
|
||||
expectedSet.add(5);
|
||||
|
||||
Set<Integer> subSet = treeSet.subSet(2, 6);
|
||||
Assert.assertEquals(expectedSet, subSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingHeadSet_shouldReturnHeadSetElements() {
|
||||
SortedSet<Integer> treeSet = new TreeSet<>();
|
||||
treeSet.add(1);
|
||||
treeSet.add(2);
|
||||
treeSet.add(3);
|
||||
treeSet.add(4);
|
||||
treeSet.add(5);
|
||||
treeSet.add(6);
|
||||
|
||||
Set<Integer> subSet = treeSet.headSet(6);
|
||||
Assert.assertEquals(subSet, treeSet.subSet(1, 6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTailSet_shouldReturnTailSetElements() {
|
||||
NavigableSet<Integer> treeSet = new TreeSet<>();
|
||||
treeSet.add(1);
|
||||
treeSet.add(2);
|
||||
treeSet.add(3);
|
||||
treeSet.add(4);
|
||||
treeSet.add(5);
|
||||
treeSet.add(6);
|
||||
|
||||
Set<Integer> subSet = treeSet.tailSet(3);
|
||||
Assert.assertEquals(subSet, treeSet.subSet(3, true, 6, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.java.collections;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ConcurrentModificationExceptionUnitTest {
|
||||
|
||||
@Test
|
||||
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
|
||||
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));
|
||||
|
||||
for (Object item : array) {
|
||||
array.set(3, 3);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removingElementUsingIteratorAPI() throws Exception {
|
||||
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
|
||||
|
||||
Iterator<String> iterator = originalList.iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
String next = iterator.next();
|
||||
if (Objects.equals(next, "one")) iterator.remove();
|
||||
}
|
||||
|
||||
assertEquals(originalList, asList("zero", "two", "three"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyingContentAndIteratingUsingListIteratorAPI() throws Exception {
|
||||
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
|
||||
|
||||
ListIterator<String> iterator = originalList.listIterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
String next = iterator.next();
|
||||
if (Objects.equals(next, "one")) {
|
||||
iterator.set("another");
|
||||
}
|
||||
|
||||
if (Objects.equals(next, "two")) {
|
||||
iterator.remove();
|
||||
}
|
||||
|
||||
if (Objects.equals(next, "three")) {
|
||||
iterator.add("four");
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(originalList, asList("zero", "another", "three", "four"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removingElementUsingCopyAndListAPI() throws Exception {
|
||||
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
|
||||
|
||||
List<String> listCopy = new ArrayList<>(originalList);
|
||||
|
||||
for (String next : listCopy) {
|
||||
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
|
||||
}
|
||||
|
||||
assertEquals(originalList, asList("one", "two", "three"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copyOnWriteList() throws Exception {
|
||||
List<String> originalList = new CopyOnWriteArrayList<>(asList("zero", "one", "two", "three"));
|
||||
|
||||
for (String next : originalList) {
|
||||
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
|
||||
}
|
||||
|
||||
assertEquals(originalList, asList("one", "two", "three"));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class MapUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class);
|
||||
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
assertEquals(2, keys.size());
|
||||
assertTrue(keys.contains("name"));
|
||||
assertTrue(keys.contains("type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesValues_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Collection<String> values = map.values();
|
||||
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains("baeldung"));
|
||||
assertTrue(values.contains("blog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<Entry<String, String>> entries = map.entrySet();
|
||||
|
||||
assertEquals(2, entries.size());
|
||||
for (Entry<String, String> e : entries) {
|
||||
String key = e.getKey();
|
||||
String val = e.getValue();
|
||||
assertTrue(key.equals("name") || key.equals("type"));
|
||||
assertTrue(val.equals("baeldung") || val.equals("blog"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
assertEquals(2, map.size());
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
keys.remove("name");
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
Iterator<String> it = keys.iterator();
|
||||
map.remove("type");
|
||||
while (it.hasNext()) {
|
||||
String key = it.next();
|
||||
}
|
||||
}
|
||||
|
||||
public void givenIterator_whenRemoveWorks_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
Iterator<String> it = keys.iterator();
|
||||
while (it.hasNext()) {
|
||||
it.next();
|
||||
it.remove();
|
||||
}
|
||||
assertEquals(0, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHashCodeIsCalledOnPut_thenCorrect() {
|
||||
MyKey key = new MyKey(1, "name");
|
||||
Map<MyKey, String> map = new HashMap<>();
|
||||
map.put(key, "val");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHashCodeIsCalledOnGet_thenCorrect() {
|
||||
MyKey key = new MyKey(1, "name");
|
||||
Map<MyKey, String> map = new HashMap<>();
|
||||
map.put(key, "val");
|
||||
map.get(key);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetWorks_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "val");
|
||||
|
||||
String val = map.get("key");
|
||||
|
||||
assertEquals("val", val);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.put("key1", "val1");
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.get("key1");
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.put("key1", null);
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullKeyAndVal_whenAccepts_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
map.put(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullVal_whenRetrieves_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", null);
|
||||
|
||||
String val = map.get("key");
|
||||
|
||||
assertNull(val);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenContainsDistinguishesNullValues_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String val1 = map.get("key");
|
||||
boolean valPresent = map.containsKey("key");
|
||||
|
||||
assertNull(val1);
|
||||
assertFalse(valPresent);
|
||||
|
||||
map.put("key", null);
|
||||
String val = map.get("key");
|
||||
valPresent = map.containsKey("key");
|
||||
|
||||
assertNull(val);
|
||||
assertTrue(valPresent);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutReturnsPrevValue_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "val1");
|
||||
String rtnVal = map.put("key1", "val2");
|
||||
|
||||
assertEquals("val1", rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||
HashMap<MyKey, String> map = new HashMap<>();
|
||||
MyKey k1 = new MyKey(1, "firstKey");
|
||||
MyKey k2 = new MyKey(2, "secondKey");
|
||||
MyKey k3 = new MyKey(2, "thirdKey");
|
||||
|
||||
LOG.debug("storing value for k1");
|
||||
map.put(k1, "firstValue");
|
||||
|
||||
LOG.debug("storing value for k2");
|
||||
map.put(k2, "secondValue");
|
||||
|
||||
LOG.debug("storing value for k3");
|
||||
map.put(k3, "thirdValue");
|
||||
|
||||
LOG.debug("retrieving value for k1");
|
||||
String v1 = map.get(k1);
|
||||
|
||||
LOG.debug("retrieving value for k2");
|
||||
String v2 = map.get(k2);
|
||||
|
||||
LOG.debug("retrieving value for k3");
|
||||
String v3 = map.get(k3);
|
||||
|
||||
assertEquals("firstValue", v1);
|
||||
assertEquals("secondValue", v2);
|
||||
assertEquals("thirdValue", v3);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
Integer[] arr = keys.toArray(new Integer[0]);
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
assertEquals(new Integer(i + 1), arr[i]);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||
map.get(4);
|
||||
assertEquals("[1, 2, 3, 5, 4]", keys.toString());
|
||||
map.get(1);
|
||||
assertEquals("[2, 3, 5, 4, 1]", keys.toString());
|
||||
map.get(3);
|
||||
assertEquals("[2, 5, 4, 1, 3]", keys.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new MyLinkedHashMap<>(16, .75f, true);
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||
map.put(6, null);
|
||||
assertEquals("[2, 3, 4, 5, 6]", keys.toString());
|
||||
map.put(7, null);
|
||||
assertEquals("[3, 4, 5, 6, 7]", keys.toString());
|
||||
map.put(8, null);
|
||||
assertEquals("[4, 5, 6, 7, 8]", keys.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>();
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() {
|
||||
TreeMap<String, String> map = new TreeMap<>();
|
||||
map.put("c", "val");
|
||||
map.put("b", "val");
|
||||
map.put("a", "val");
|
||||
map.put("e", "val");
|
||||
map.put("d", "val");
|
||||
|
||||
assertEquals("[a, b, c, d, e]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenPerformsQueries_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>();
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
Integer highestKey = map.lastKey();
|
||||
Integer lowestKey = map.firstKey();
|
||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||
Set<Integer> keysGreaterThanEqTo3 = map.tailMap(3).keySet();
|
||||
|
||||
assertEquals(new Integer(5), highestKey);
|
||||
assertEquals(new Integer(1), lowestKey);
|
||||
assertEquals("[1, 2]", keysLessThan3.toString());
|
||||
assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.weakhashmap;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WeakHashMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImage = new BigImage("image_id");
|
||||
UniqueImageName imageName = new UniqueImageName("name_of_big_image");
|
||||
|
||||
map.put(imageName, bigImage);
|
||||
assertTrue(map.containsKey(imageName));
|
||||
|
||||
//when big image key is not reference anywhere
|
||||
imageName = null;
|
||||
System.gc();
|
||||
|
||||
//then GC will finally reclaim that object
|
||||
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImageFirst = new BigImage("foo");
|
||||
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
|
||||
|
||||
BigImage bigImageSecond = new BigImage("foo_2");
|
||||
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
|
||||
|
||||
map.put(imageNameFirst, bigImageFirst);
|
||||
map.put(imageNameSecond, bigImageSecond);
|
||||
assertTrue(map.containsKey(imageNameFirst));
|
||||
assertTrue(map.containsKey(imageNameSecond));
|
||||
|
||||
//when
|
||||
imageNameFirst = null;
|
||||
System.gc();
|
||||
|
||||
//then
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
|
||||
}
|
||||
|
||||
|
||||
class BigImage {
|
||||
public final String imageId;
|
||||
|
||||
BigImage(String imageId) {
|
||||
this.imageId = imageId;
|
||||
}
|
||||
}
|
||||
|
||||
class UniqueImageName {
|
||||
public final String imageName;
|
||||
|
||||
UniqueImageName(String imageName) {
|
||||
this.imageName = imageName;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user