From b4e217c8a91272a63b5c5ec103031ed0397530f0 Mon Sep 17 00:00:00 2001 From: Ken Kousen Date: Tue, 17 Sep 2024 11:58:04 -0400 Subject: [PATCH] Add random number generation and map iteration tests Extended SummarizingDemo with random number generation and statistics computation. Introduced a new test in FileFilterTest to demonstrate iteration over a map using both pre-Java 8 and Java 8+ approaches. --- src/main/java/SummarizingDemo.java | 14 ++++++++++++++ src/test/java/lambdas/FileFilterTest.java | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/main/java/SummarizingDemo.java b/src/main/java/SummarizingDemo.java index afd0440..cd76db5 100644 --- a/src/main/java/SummarizingDemo.java +++ b/src/main/java/SummarizingDemo.java @@ -13,5 +13,19 @@ public static void main(String[] args) { System.out.println(stats.getAverage()); System.out.println(stats.getMax()); System.out.println(stats.getSum()); + + System.out.println(); + DoubleStream.generate(Math::random) + .limit(10) + .forEach(System.out::println); + + System.out.println(); + stats = DoubleStream.generate(Math::random) + .limit(10) + .peek(x -> System.out.println("before mapping " + x)) + .map(x -> x * 100) + .peek(x -> System.out.println("after mapping " + x)) + .summaryStatistics(); + System.out.println(stats); } } diff --git a/src/test/java/lambdas/FileFilterTest.java b/src/test/java/lambdas/FileFilterTest.java index 948bd0a..044995b 100644 --- a/src/test/java/lambdas/FileFilterTest.java +++ b/src/test/java/lambdas/FileFilterTest.java @@ -4,6 +4,7 @@ import java.io.File; import java.io.FileFilter; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -79,4 +80,15 @@ void listJavaSrcFiles_filenameFilter() { assert javaFiles != null; assertEquals(8, javaFiles.length); } + + @Test + void iterateOverMap() { + var map = Map.of("a", 1, "b", 2, "c", 3); + // Before Java 8: + for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + + map.forEach((k, v) -> System.out.println(k + " -> " + v)); + } }