1+ package com .baeldung .java .list ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+
5+ import java .util .ArrayList ;
6+ import java .util .Arrays ;
7+ import java .util .Iterator ;
8+ import java .util .List ;
9+ import java .util .ListIterator ;
10+
11+ import org .junit .Test ;
12+
13+ public class WaysToIterateUnitTest {
14+
15+ List <String > globalCountries = new ArrayList <String >();
16+ List <String > europeanCountries = Arrays .asList ("Germany" , "Panama" , "Australia" );
17+
18+ @ Test
19+ public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList () {
20+ for (int i = 0 ; i < europeanCountries .size (); i ++) {
21+ globalCountries .add (europeanCountries .get (i ));
22+ }
23+ assertEquals (globalCountries .size (), 3 );
24+ globalCountries .clear ();
25+ }
26+
27+ @ Test
28+ public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList () {
29+ for (String country : europeanCountries ) {
30+ globalCountries .add (country );
31+ }
32+ assertEquals (globalCountries .size (), 3 );
33+ globalCountries .clear ();
34+ }
35+
36+ @ Test
37+ public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList () {
38+ Iterator <String > countriesIterator = europeanCountries .iterator ();
39+ while (countriesIterator .hasNext ()) {
40+ globalCountries .add (countriesIterator .next ());
41+ }
42+
43+ assertEquals (globalCountries .size (), 3 );
44+ globalCountries .clear ();
45+ }
46+
47+ @ Test
48+ public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList () {
49+ ListIterator <String > countriesIterator = europeanCountries .listIterator ();
50+ while (countriesIterator .hasNext ()) {
51+ globalCountries .add (countriesIterator .next ());
52+ }
53+
54+ assertEquals (globalCountries .size (), 3 );
55+ globalCountries .clear ();
56+ }
57+
58+ @ Test
59+ public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList () {
60+ europeanCountries .forEach (country -> globalCountries .add (country ));
61+ assertEquals (globalCountries .size (), 3 );
62+ globalCountries .clear ();
63+ }
64+
65+ @ Test
66+ public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList () {
67+ europeanCountries .stream ().forEach ((country ) -> globalCountries .add (country ));
68+ assertEquals (globalCountries .size (), 3 );
69+ globalCountries .clear ();
70+ }
71+ }
0 commit comments