Skip to content

Commit

Permalink
Optimized code and improved readability in LazyStreams and LoopsSorts…
Browse files Browse the repository at this point in the history
…AndIfs

In LazyStreams.java, the redundant call to Logger class is removed which is not used in the rest of the file. This optimizes memory use. In the firstEvenDoubleDivBy3 function, sequence of function calls is rearranged to avoid unnecessary operations when the stream is parallelized.

In LoopsSortsAndIfs.java, traditional for loops are replaced with Java 8 Streams to increase code readability and conciseness. The resulting code is more streamlined and efficient. The processing steps are visible in one line, enabling easier understanding and maintenance.
  • Loading branch information
kousen committed Nov 8, 2023
1 parent b41160e commit a71aad3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 26 deletions.
8 changes: 3 additions & 5 deletions src/main/java/lazy/LazyStreams.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package lazy;

import java.util.logging.Logger;
import java.util.stream.IntStream;

public class LazyStreams {
private static final Logger logger = Logger.getLogger(LazyStreams.class.getName());

public static int multByTwo(int n) {
System.out.printf("Inside multByTwo with arg %d on thread %s%n",
n, Thread.currentThread().getName());
Expand All @@ -29,9 +26,10 @@ public static void main(String[] args) {

// Demonstrate laziness using print statements
firstEvenDoubleDivBy3 = IntStream.rangeClosed(100, 2_000_000)
// .parallel()
.filter(LazyStreams::modByThree)
.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
29 changes: 8 additions & 21 deletions src/main/java/refactoring/after/LoopsSortsAndIfs.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,17 @@
package refactoring.after;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

public class LoopsSortsAndIfs {
public static void main(String[] args) {
String[] strings = "this is an array of strings".split(" ");

List<String> evenLengths = new ArrayList<>();
for (String s : strings) {
if (s.length() % 2 == 0) {
evenLengths.add(s.toUpperCase());
}
}
Arrays.stream("this is an array of strings".split(" "))
.filter(s -> s.length() % 2 == 0)
.map(String::toUpperCase)
.sorted(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()))
.forEach(System.out::println);

Collections.sort(evenLengths, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});

for (String s : evenLengths) {
System.out.println(s);
}
}
}

0 comments on commit a71aad3

Please sign in to comment.