From 0884539efdb46a00efbb7fbd7ac28dfd4dc04697 Mon Sep 17 00:00:00 2001 From: CristianLopez3 Date: Sun, 9 Jun 2024 23:16:12 -0500 Subject: [PATCH] get a better understanding of flat map --- .../finance/programming/UsageOfFlatMap.java | 56 +++++++++++++++++++ tests.md | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/finance/programming/UsageOfFlatMap.java diff --git a/src/test/java/com/finance/programming/UsageOfFlatMap.java b/src/test/java/com/finance/programming/UsageOfFlatMap.java new file mode 100644 index 0000000..1c9f59d --- /dev/null +++ b/src/test/java/com/finance/programming/UsageOfFlatMap.java @@ -0,0 +1,56 @@ +package com.finance.programming; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("Usage of flatMap in Java 8 Streams") +public class UsageOfFlatMap { + + @Test + @DisplayName("Flattening a 2D array using flatMap") + void testFlattening2DArray() { + int[][] twoDArray = {{1, 2}, {3, 4}, {5, 6}}; + int[] expectedArray = {1, 2, 3, 4, 5, 6}; + + int[] oneDArray = Arrays.stream(twoDArray) + .flatMapToInt(Arrays::stream) + .toArray(); + + assertArrayEquals(expectedArray, oneDArray); + + } + + @Test + @DisplayName("Flattening a 2D array using flatMap") + void testFlatteningAListOfInteger() { + List> twoDList = List.of( + List.of(1, 2), + List.of(3, 4), + List.of(5, 6) + ); + + List expectedList = List.of(1, 2, 3, 4, 5, 6); + + Function, Stream> returnJustOneList = Collection::stream; + + List actualList = twoDList.stream() + .flatMap(returnJustOneList::apply) + .toList(); + + assertIterableEquals(expectedList, actualList, () -> { + System.out.println("Expected List: " + expectedList); + System.out.println("Actual List: " + actualList); + return "The content of the list doesn't match"; + }); + + } + +} diff --git a/tests.md b/tests.md index 8a63272..b75b5b8 100644 --- a/tests.md +++ b/tests.md @@ -28,7 +28,7 @@ Description: Take a list of strings and use map to convert all strings to upperc ✔️ **Exercise 8: Reducing a list** Description: Use reduce to sum all the elements of a list of integers. -❌ **Exercise 9: Using flatMap** +✔️ **Exercise 9: Using flatMap** Description: Take a list of lists of integers and use flatMap to convert it into a flat list of integers. ❌ **Exercise 10: Sorting a list**