Skip to content

Commit

Permalink
Improve code clarity and efficiency in LazyStreams and UsePerson files
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kousen committed Nov 8, 2023
1 parent a71aad3 commit a057083
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/main/java/lambdas/UsePerson.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -49,7 +49,7 @@ public static void main(String[] args) {
LinkedList<Person> linkedPersons = names.stream()
.map(Person::new)
.collect(
() -> new LinkedList<Person>(), // Supplier<LinkedList>
() -> new LinkedList<>(), // Supplier<LinkedList>
(list, person) -> list.add(person), // BiConsumer<LinkedList, Person>
(list1, list2) -> list1.addAll(list2)); // BiConsumer<LinkedList, LinkedList>
System.out.println(linkedPersons);
Expand Down
9 changes: 7 additions & 2 deletions src/main/java/lazy/LazyStreams.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,23 @@ 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);


// 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);
}
Expand Down

0 comments on commit a057083

Please sign in to comment.