Skip to content

Commit

Permalink
get a better understanding of flat map
Browse files Browse the repository at this point in the history
  • Loading branch information
CristianLopez3 committed Jun 10, 2024
1 parent 73b5e20 commit 0884539
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
56 changes: 56 additions & 0 deletions src/test/java/com/finance/programming/UsageOfFlatMap.java
Original file line number Diff line number Diff line change
@@ -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<List<Integer>> twoDList = List.of(
List.of(1, 2),
List.of(3, 4),
List.of(5, 6)
);

List<Integer> expectedList = List.of(1, 2, 3, 4, 5, 6);

Function<List<Integer>, Stream<Integer>> returnJustOneList = Collection::stream;

List<Integer> 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";
});

}

}
2 changes: 1 addition & 1 deletion tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down

0 comments on commit 0884539

Please sign in to comment.