diff --git a/core-java-modules/core-java-collections-list-4/pom.xml b/core-java-modules/core-java-collections-list-4/pom.xml index 49b3f849d4..86b3bde821 100644 --- a/core-java-modules/core-java-collections-list-4/pom.xml +++ b/core-java-modules/core-java-collections-list-4/pom.xml @@ -62,6 +62,12 @@ ${spring.version} test + + org.springframework.data + spring-data-commons + 2.7.5 + test + diff --git a/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/iteration/IterateListSimultaneouslyUnitTest.java b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/iteration/IterateListSimultaneouslyUnitTest.java new file mode 100644 index 0000000000..50e83800d8 --- /dev/null +++ b/core-java-modules/core-java-collections-list-4/src/test/java/com/baeldung/list/iteration/IterateListSimultaneouslyUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.list.iteration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.springframework.data.util.StreamUtils; + +public class IterateListSimultaneouslyUnitTest { + + final List countryName = List.of("USA", "UK", "Germany", "India"); + final List countryCode = List.of("+1", "+44", "+49", "+91"); + + @Test + public void givenTwoLists_whenProcessedByZipping_thenGetJoinedDataFromBothCollections() { + List processedList = StreamUtils.zip(countryName.stream(), countryCode.stream(), + (name, code) -> String.format("%s: %s", name, code)) + .collect(Collectors.toList()); + assertThat(processedList).containsExactly("USA: +1", "UK: +44", "Germany: +49", "India: +91"); + } + + @Test + public void givenTwoLists_whenIterateUsingIterator_thenGetJoinedDataFromBothCollections() { + Iterator nameIterator = countryName.iterator(); + Iterator codeIterator = countryCode.iterator(); + List processedList = new ArrayList<>(); + while (nameIterator.hasNext() && codeIterator.hasNext()) { + String processedData = String.format("%s: %s", nameIterator.next(), codeIterator.next()); + processedList.add(processedData); + } + assertThat(processedList).containsExactly("USA: +1", "UK: +44", "Germany: +49", "India: +91"); + } + + @Test + public void givenTwoLists_whenIterateUsingLoop_thenGetJoinedDataFromBothCollections() { + List processedList = new ArrayList<>(); + for (int i = 0; i < countryName.size(); i++) { + String processedData = String.format("%s: %s", countryName.get(i), countryCode.get(i)); + processedList.add(processedData); + } + assertThat(processedList).containsExactly("USA: +1", "UK: +44", "Germany: +49", "India: +91"); + } + +}