Skip to content

Commit

Permalink
Refactor Employee interface and CompanyEmployee class to use Java rec…
Browse files Browse the repository at this point in the history
…ords

In the Employee interface, getter method names were altered for brevity and to align better with the Java record conventions used in the following change. The getters `getFirst()` and `getLast()` were altered to simply `first()` and `last()`.

The CompanyEmployee class was changed from a regular class to a Java record. This change makes for more concise code and eliminates the need for explicit getter methods and a constructor. As part of this change, the `getFirst()` and `getLast()` methods were removed, because they are implicitly provided by the record.

The StringExercise class was edited to include various stream operations and examples of their use for sorting and filtering collections.

The Golfer class inside the sorting package was updated to use `Objects.equals()` for comparison in the equals method, for better readability and null-safety.

Overall, these changes modernize the codebase to take advantage of newer Java features and to improve code readability.
  • Loading branch information
kousen committed Sep 26, 2023
1 parent 6fcfd4d commit 2e2fd0b
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 30 deletions.
23 changes: 6 additions & 17 deletions src/main/java/interfaces/CompanyEmployee.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,19 @@
package interfaces;

public class CompanyEmployee implements Company, Employee {
private final String first;
private final String last;
// Records in Java:
// - immutable data holders
// - primary constructor outside the braces {}
// - automatically generate toString, equals, and hashCode
// - "getters" match the names of the attributes

public CompanyEmployee(String first, String last) {
this.first = first;
this.last = last;
}
public record CompanyEmployee(String first, String last) implements Company, Employee {

@Override
public String getName() {
return Employee.super.getName() + " works for " +
Company.super.getName();
}

@Override
public String getFirst() {
return first;
}

@Override
public String getLast() {
return last;
}

@Override
public void doWork() {
System.out.println("Converting caffeine into code for $$...");
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/interfaces/Employee.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package interfaces;

public interface Employee {
String getFirst();
String first();

String getLast();
String last();

void doWork();

default String getName() {
return String.format("%s %s", getFirst(), getLast());
return String.format("%s %s", first(), last());
}
}
6 changes: 4 additions & 2 deletions src/main/java/sorting/Golfer.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package sorting;

import java.util.Objects;

public class Golfer implements Comparable<Golfer> {
private String first;
private String last;
Expand Down Expand Up @@ -54,8 +56,8 @@ public boolean equals(Object o) {

Golfer golfer = (Golfer) o;

if (first != null ? !first.equals(golfer.first) : golfer.first != null) return false;
return last != null ? last.equals(golfer.last) : golfer.last == null;
if (!Objects.equals(first, golfer.first)) return false;
return Objects.equals(last, golfer.last);

}

Expand Down
61 changes: 53 additions & 8 deletions src/test/java/streams/StringExercises.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class StringExercises {
private final List<String> strings = Arrays.asList("this", "is", "a",
"list", "of", "strings");
private final List<String> strings = Arrays.asList(
"this", "is", "a", "list", "of", "strings");

@Test
public void stringLengthSort_InnerClass() { // Java 5, 6, 7
Expand All @@ -25,8 +27,14 @@ public int compare(String s1, String s2) {
@Test
public void stringLengthSort_lambda() {
// Use lambda for the Comparator (reverse sort)
strings.sort((s1, s2) -> s2.length() - s1.length());
System.out.println(strings);

// Use the "sorted" method on Stream
strings.stream()
.sorted((s1, s2) -> s1.length() - s2.length())
.forEach(System.out::println);
System.out.println(strings);
}

private int compareStrings(String s1, String s2) {
Expand All @@ -35,31 +43,68 @@ private int compareStrings(String s1, String s2) {

@Test // Use a lambda that calls 'compareStrings' directly
public void stringLengthSort_methodCall() {

strings.stream()
.sorted((s1, s2) -> compareStrings(s1, s2))
.forEach(System.out::println);
}

@Test // Use a method ref to 'compareStrings'
public void stringLengthSort_methodRef() {

strings.stream()
.sorted(this::compareStrings)
.forEach(System.out::println);
}

@Test // Use Comparator.comparingInt
public void stringLengthSort_comparingInt() {

List<String> sorted = strings.stream()
.sorted(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()))
.collect(Collectors.toList());
System.out.println(sorted);
System.out.println(sorted.getClass().getName());
}

@Test
public void demoCollectors() {
// Get only strings of even length
// Add them to a LinkedList
LinkedList<String> evens = strings.stream()
.filter(s -> s.length() % 2 == 0)
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(evens);

// Add the strings to a map of string to length
Map<String, Integer> map = strings.stream()
// .collect(Collectors.toMap(s -> s, String::length));
.collect(Collectors.toMap(Function.identity(), String::length));
map.forEach((k, v) -> System.out.println(k + " -> " + v));

// Filter out nulls, then print even-length strings
List<String> stringsWithNulls = Arrays.asList(
"this", null, "is", null, "a", "list", "of", "strings", null, null);

// short-circuiting logical AND
List<String> evenLengths = stringsWithNulls.stream()
// .filter(s -> s != null && s.length() % 2 == 0)
.filter(Objects::nonNull)
.filter(s -> s.length() % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenLengths);

// Consumers for printing and logging
Logger logger = Logger.getLogger(StringExercises.class.getName());
Consumer<String> log = logger::info;
Consumer<String> print = System.out::println;

// Function composition
Predicate<String> nonNull = Objects::nonNull;
Predicate<String> evenLength = s -> s.length() % 2 == 0;

// Combine the two predicates and use the result to print non-null, even-length strings
stringsWithNulls.stream()
.filter(nonNull.and(evenLength))
.forEach(print.andThen(log));

// f: A -> B, g: B -> C, (g.f)(x) = g(f(x)), A -> C
}
Expand Down

0 comments on commit 2e2fd0b

Please sign in to comment.