Skip to content

Commit a1ba371

Browse files
fscorromaibin
authored andcommitted
add elements to list (eugenp#4814)
1 parent 81027b7 commit a1ba371

1 file changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.baeldung.list;
2+
3+
import org.junit.Assert;
4+
import org.junit.Before;
5+
import org.junit.Test;
6+
7+
import java.util.*;
8+
9+
import static org.junit.Assert.*;
10+
11+
public class AddElementsUnitTest {
12+
13+
List<Flower> flowers;
14+
15+
@Before
16+
public void init() {
17+
this.flowers = new ArrayList<>(Arrays.asList(
18+
new Flower("Poppy", 12),
19+
new Flower("Anemone", 8),
20+
new Flower("Catmint", 12)));
21+
}
22+
23+
@Test
24+
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
25+
List<Flower> anotherList = new ArrayList<>();
26+
anotherList.addAll(flowers);
27+
28+
assertEquals(anotherList.size(), flowers.size());
29+
Assert.assertTrue(anotherList.containsAll(flowers));
30+
}
31+
32+
@Test
33+
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
34+
List<Flower> anotherList = new ArrayList<>();
35+
anotherList.addAll(flowers);
36+
37+
Flower flower = anotherList.get(0);
38+
flower.setPetals(flowers.get(0).getPetals() * 3);
39+
40+
assertEquals(anotherList.size(), flowers.size());
41+
Assert.assertTrue(anotherList.containsAll(flowers));
42+
}
43+
44+
@Test
45+
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
46+
List<Flower> target = new ArrayList<>();
47+
48+
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
49+
50+
assertEquals(target.size(), 4);
51+
}
52+
53+
@Test
54+
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
55+
List<Flower> flowerVase = new ArrayList<>();
56+
57+
flowers.stream()
58+
.skip(1)
59+
.forEachOrdered(flowerVase::add);
60+
61+
assertEquals(flowerVase.size() + 1, flowers.size());
62+
assertFalse(flowerVase.containsAll(flowers));
63+
}
64+
65+
@Test
66+
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
67+
List<Flower> flowerVase = new ArrayList<>();
68+
69+
flowers.stream()
70+
.filter(f -> f.getPetals() > 10)
71+
.forEachOrdered(flowerVase::add);
72+
73+
assertEquals(flowerVase.size() + 1, flowers.size());
74+
assertFalse(flowerVase.containsAll(flowers));
75+
}
76+
77+
@Test
78+
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
79+
List<Flower> target = new ArrayList<>();
80+
81+
Optional.ofNullable(flowers)
82+
.ifPresent(target::addAll);
83+
84+
assertNotNull(target);
85+
assertEquals(target.size(), 3);
86+
}
87+
}

0 commit comments

Comments
 (0)