Skip to content

Commit

Permalink
Refactor code to use modern Java features
Browse files Browse the repository at this point in the history
Code has been updated across multiple files to use more modern Java features. These changes include modifying loops and if statements to use streams, replacing a ArrayList with List.of() for immutability, introducing new record PersonRecord, and updating error logging in LazyStreams. This code cleanup improves readability and makes better use of Java's capabilities.
  • Loading branch information
kousen committed Dec 11, 2023
1 parent 41dff39 commit a6d73c6
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 36 deletions.
10 changes: 10 additions & 0 deletions src/main/java/SummarizingDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@
import java.util.stream.DoubleStream;

public class SummarizingDemo {

public static DoubleStream getLimitedRandomStream(int limit) {
return DoubleStream.generate(Math::random).limit(limit);
}

public static void main(String[] args) {
DoubleStream doubleStream = getLimitedRandomStream(10);

doubleStream.forEach(System.out::println);
// doubleStream.forEach(System.out::println);

DoubleSummaryStatistics stats = DoubleStream.generate(Math::random)
.limit(1_000_000)
.summaryStatistics();
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/lambdas/Person.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ public void setName(String name) {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;

Person person = (Person) o;

// pattern matching for instanceof
if (!(o instanceof Person person)) return false;
return Objects.equals(name, person.name);
}

Expand Down
23 changes: 23 additions & 0 deletions src/main/java/lambdas/PersonRecord.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package lambdas;

// Records:
// - are immutable data holders
// - automatically generate equals(), hashCode(), and toString()
// - "getters" match the property names, as in "name()"
// - primary constructor is declared before the braces {}
public record PersonRecord(String name) {

public PersonRecord(String first, String last) {
this(first + " " + last);
}

// Copy constructor
public PersonRecord(PersonRecord other) {
this(other.name);
}

public PersonRecord(String... names) {
this(String.join(" ", names));
}

}
22 changes: 16 additions & 6 deletions src/main/java/lambdas/UsePerson.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
import java.util.stream.Collectors;

public class UsePerson {
@SuppressWarnings("Convert2MethodRef")
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Paul", "George", "Ringo");
List<String> names = List.of("John", "Paul", "George", "Ringo");

// Old-style way:
List<Person> beatles = new ArrayList<>(); // Shared mutable state
Expand All @@ -17,14 +18,15 @@ public static void main(String[] args) {
}
System.out.println(beatles);

@SuppressWarnings("Convert2MethodRef")
List<Person> people = names.stream() // Stream<String>
.map(name -> new Person(name)) // Stream<Person>
.collect(Collectors.toList()); // Converts Stream<Person> to List<Person>
System.out.println(people);

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(String) ctr
.map(Person::new) // uses the Person(Person) ctr
.collect(Collectors.toList());
System.out.println(people);

Expand All @@ -46,12 +48,15 @@ public static void main(String[] args) {
// p1..p5 | p6..p10 | p11..p15 | p16..p20 // say you have 4 cores and run in parallel
// l1 l2 l3 l4
// list
LinkedList<Person> linkedPersons = names.stream()
LinkedList<Person> linkedPersons = names.parallelStream()
.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>
(list1, list2) -> {
System.out.println("processing " + list1 + " and " + list2);
list1.addAll(list2);
}); // BiConsumer<LinkedList, LinkedList>
System.out.println(linkedPersons);

linkedPersons = names.stream()
Expand All @@ -66,5 +71,10 @@ public static void main(String[] args) {
.map(Person::new)
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(linkedPersons);

List<PersonRecord> records = names.stream()
.map(PersonRecord::new)
.toList(); // added in Java 16, produces immutable collections
System.out.println(records);
}
}
5 changes: 1 addition & 4 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 @@ -30,8 +27,8 @@ 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)
.filter(LazyStreams::modByThree)
.findFirst().orElse(0);
System.out.printf("First even divisible by 3 is %d%n", firstEvenDoubleDivBy3);
}
Expand Down
29 changes: 7 additions & 22 deletions src/main/java/refactoring/after/LoopsSortsAndIfs.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,15 @@
package refactoring.after;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

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());
}
}

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);
}
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);
}
}

0 comments on commit a6d73c6

Please sign in to comment.