From a0570839fdf1db1ab6e70384a47f3788ca817c18 Mon Sep 17 00:00:00 2001 From: Ken Kousen Date: Wed, 8 Nov 2023 14:27:36 -0700 Subject: [PATCH] Improve code clarity and efficiency in LazyStreams and UsePerson files In LazyStreams.java, added print statements to help track how stream elements are processed step by step; this aids in understanding the lazy processing distinctive feature of streams. Removed the sequential() and parallel() operations, as they were used inappropriately and weren't necessary in the current context. In UsePerson.java, the constructor in the Person class is now properly duplicated and the unnecessary explicit typing in LinkedList instantiation is eliminated. These changes help improve readability and simplicity of the code. --- src/main/java/lambdas/UsePerson.java | 4 ++-- src/main/java/lazy/LazyStreams.java | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/lambdas/UsePerson.java b/src/main/java/lambdas/UsePerson.java index a231dea..220eb7f 100644 --- a/src/main/java/lambdas/UsePerson.java +++ b/src/main/java/lambdas/UsePerson.java @@ -24,7 +24,7 @@ public static void main(String[] args) { people = names.stream() .map(Person::new) // uses the Person(String) ctr - // .map(Person::new) // uses the Person(Person) ctr + .map(Person::new) // uses the Person(Person) ctr .collect(Collectors.toList()); System.out.println(people); @@ -49,7 +49,7 @@ public static void main(String[] args) { LinkedList linkedPersons = names.stream() .map(Person::new) .collect( - () -> new LinkedList(), // Supplier + () -> new LinkedList<>(), // Supplier (list, person) -> list.add(person), // BiConsumer (list1, list2) -> list1.addAll(list2)); // BiConsumer System.out.println(linkedPersons); diff --git a/src/main/java/lazy/LazyStreams.java b/src/main/java/lazy/LazyStreams.java index a2ee7a6..08ffec4 100644 --- a/src/main/java/lazy/LazyStreams.java +++ b/src/main/java/lazy/LazyStreams.java @@ -18,8 +18,15 @@ public static boolean modByThree(int n) { public static void main(String[] args) { // multiply numbers between 100 and 200 by 2, then find first n divisible by 3 int firstEvenDoubleDivBy3 = IntStream.rangeClosed(100, 200) + .peek(n -> System.out.printf("Original: %d%n", n)) + .map(n -> { + System.out.println("Doubling " + n); + return n; + }) .map(n -> n * 2) + .peek(n -> System.out.printf("Doubled: %d%n", n)) .filter(n -> n % 3 == 0) + .peek(n -> System.out.printf("Filtered: %d%n", n)) .findFirst().orElse(0); System.out.println(firstEvenDoubleDivBy3); @@ -27,9 +34,7 @@ public static void main(String[] args) { // Demonstrate laziness using print statements firstEvenDoubleDivBy3 = IntStream.rangeClosed(100, 2_000_000) .map(LazyStreams::multByTwo) - .sequential() .filter(LazyStreams::modByThree) - .parallel() .findFirst().orElse(0); System.out.printf("First even divisible by 3 is %d%n", firstEvenDoubleDivBy3); }