Skip to content

Commit

Permalink
Enhance sorting and stream operations in tests
Browse files Browse the repository at this point in the history
Updated `StringExercises` with comprehensive stream operations, including sorting, filtering, and using collectors. Refined `SortingTest` by simplifying the sorting logic and removing the intermediate list collection step.
  • Loading branch information
kousen committed Sep 18, 2024
1 parent ee78cf7 commit 33bfd02
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 16 deletions.
12 changes: 5 additions & 7 deletions src/test/java/sorting/SortingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortingTest {

// "Getter" methods on a record match
// the property name, as in name(), priority()
record Project(String name, int priority) {}
record Project(String name, int priority) {
}

private List<Project> projects;

Expand All @@ -31,11 +31,9 @@ void setUp() {
// sort by priority, then by name
@Test
public void sortByPriorityThenName() {
List<Project> sorted = projects.stream()
.sorted(Comparator.comparingInt(Project::priority)
projects.stream()
.sorted(Comparator.comparingInt(Project::priority).reversed()
.thenComparing(Project::name))
.collect(Collectors.toList());
System.out.println(sorted);
System.out.println(projects);
.forEach(System.out::println);
}
}
81 changes: 72 additions & 9 deletions src/test/java/streams/StringExercises.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

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",
Expand All @@ -25,7 +27,8 @@ 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
}

Expand All @@ -35,33 +38,93 @@ private int compareStrings(String s1, String s2) {

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

strings.sort((s1, s2) -> compareStrings(s1, s2));
System.out.println(strings);
}

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

strings.sort(this::compareStrings);
System.out.println(strings);
}

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

strings.sort(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(strings);
}

@Test
public void demoCollectors() {
List<String> result = strings.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result);
System.out.println(result.getClass()
.getName());

// Get only strings of even length
// Add them to a LinkedList
LinkedList<String> evenLengths = strings.stream()
.filter(s -> s.length() % 2 == 0)
//.collect(Collectors.toCollection(() -> new LinkedList<>()));
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(evenLengths);
System.out.println(evenLengths.getClass()
.getName());

// Add the strings to a map of string to length
Map<String, Integer> map = strings.stream()
//.collect(Collectors.toMap(s -> s, s -> s.length())); // two lambda expressions
//.collect(Collectors.toMap(s -> s, String::length)); // lambda and method ref
.collect(Collectors.toMap(Function.identity(), String::length));
System.out.println(map);

// Filter out nulls, then print even-length strings
List<String> stringsWithNulls = Arrays.asList("this", null, "is", null, "a", "test", null);
List<String> evens = stringsWithNulls.stream()
//.filter(s -> s != null && s.length() % 2 == 0) // guard condition in a short-circuiting logical AND
//.filter(s -> s != null)
.filter(Objects::nonNull)
.filter(s -> s.length() % 2 == 0)
.collect(Collectors.toList());
System.out.println(evens);

Logger logger = Logger.getLogger(StringExercises.class.getName());
Consumer<String> log = logger::info;
Consumer<String> print = System.out::println;

// Function composition

// Combine the two predicates and use the result to print non-null, even-length strings
Predicate<String> nonNull = Objects::nonNull;
Predicate<String> evenLength = s -> s.length() % 2 == 0;
stringsWithNulls.stream()
.filter(nonNull.and(evenLength))
.forEach(log.andThen(print));

// f: A -> B, g: B -> C, (g.f)(x) = g(f(x)), A -> C
strings.stream()
.forEach(s -> predicateWithFunctionWithConsumer(
nonNull,
Object::toString,
System.out::println, s));
}

private <T> Predicate<T> combineThree(Predicate<T> predicate1,
Predicate<T> predicate2,
Predicate<T> predicate3) {
return predicate1.and(predicate2)
.and(predicate3);
}

private <T, R> void predicateWithFunctionWithConsumer(Predicate<T> predicate,
Function<T, R> function,
Consumer<R> consumer,
T t) {
if (predicate.test(t)) {
R r = function.apply(t);
consumer.accept(r);
}
}

// generated by GitHub Copilot
Expand Down

0 comments on commit 33bfd02

Please sign in to comment.