From a7b916a57dd5f211e4a6aa3eb78e3fd2e2d77f4b Mon Sep 17 00:00:00 2001 From: kousen Date: Wed, 14 Aug 2024 13:14:42 -0400 Subject: [PATCH] Add unit tests for collection operations with lambdas This commit introduces a new test class, CollectionsTest, which includes unit tests for collection operations using lambda expressions. The tests cover functional approaches and highlight differences in order respect for parallel streams and the use of forEach. This addition will aid in verifying the behavior of collection processing methods more effectively. --- src/test/java/lambdas/CollectionsTest.java | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/test/java/lambdas/CollectionsTest.java diff --git a/src/test/java/lambdas/CollectionsTest.java b/src/test/java/lambdas/CollectionsTest.java new file mode 100644 index 0000000..ade57cf --- /dev/null +++ b/src/test/java/lambdas/CollectionsTest.java @@ -0,0 +1,39 @@ +package lambdas; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +public class CollectionsTest { + + @Test + void forEach_with_collections() { + List strings = List.of("this", "is", "a", "list", "of", "strings"); + List lengths = new ArrayList<>(); + + // Old school, but may have concurrency issues + for (String string : strings) { + lengths.add(string.length()); + } + System.out.println(lengths); + + // functional way (collect respects "order") + lengths = strings.parallelStream() + .peek(x -> System.out.println(x + "on thread " + Thread.currentThread().getName())) + .map(String::length) + .collect(Collectors.toList()); + System.out.println(lengths); + + // forEach does NOT respect order + List stringLengths = new ArrayList<>(); + strings.parallelStream().forEachOrdered( str -> stringLengths.add(str.length())); + System.out.println(stringLengths); + + Map map = Map.of("a", 1, "b", 2, "c", 2); + map.forEach((key, value) -> System.out.println(key + ": " + value)); + } +}