Skip to content

Commit

Permalink
Add unit tests for collection operations with lambdas
Browse files Browse the repository at this point in the history
This commit introduces a new test class, CollectionsTest, which includes unit tests for collection operations using lambda expressions. The tests cover functional approaches and highlight differences in order respect for parallel streams and the use of forEach. This addition will aid in verifying the behavior of collection processing methods more effectively.
  • Loading branch information
kousen committed Aug 14, 2024
1 parent 9f08b66 commit a7b916a
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/test/java/lambdas/CollectionsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package lambdas;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class CollectionsTest {

@Test
void forEach_with_collections() {
List<String> strings = List.of("this", "is", "a", "list", "of", "strings");
List<Integer> lengths = new ArrayList<>();

// Old school, but may have concurrency issues
for (String string : strings) {
lengths.add(string.length());
}
System.out.println(lengths);

// functional way (collect respects "order")
lengths = strings.parallelStream()
.peek(x -> System.out.println(x + "on thread " + Thread.currentThread().getName()))
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths);

// forEach does NOT respect order
List<Integer> stringLengths = new ArrayList<>();
strings.parallelStream().forEachOrdered( str -> stringLengths.add(str.length()));
System.out.println(stringLengths);

Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 2);
map.forEach((key, value) -> System.out.println(key + ": " + value));
}
}

0 comments on commit a7b916a

Please sign in to comment.