Merge branch 'eugenp:master' into master

This commit is contained in:
Wynn Teo
2024-03-27 11:51:37 +08:00
committed by GitHub
346 changed files with 3876 additions and 437 deletions
@@ -12,4 +12,6 @@
- [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits)
- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence)
- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree)
- [Check if a Number Is a Happy Number in Java](https://www.baeldung.com/java-happy-sad-number-test)
- [Find the Largest Number Possible After Removing k Digits of a Number](https://www.baeldung.com/java-find-largest-number-remove-k-digits)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
@@ -0,0 +1,82 @@
package com.baeldung.algorithms.happynumber;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HappyNumberDecider {
public static boolean isHappyNumber(int n) {
Set<Integer> checkedNumbers = new HashSet<>();
while (true) {
n = sumDigitsSquare(n);
if (n == 1) {
return true;
}
if (checkedNumbers.contains(n)) {
return false;
}
checkedNumbers.add(n);
}
}
public static boolean isHappyNumberFloyd(int n) {
int slow = n;
int fast = n;
do {
slow = sumDigitsSquare(slow);
fast = sumDigitsSquare(sumDigitsSquare(fast));
} while (slow != fast);
return slow == 1;
}
private static int sumDigitsSquare(int n) {
int squareSum = 0;
while (n != 0) {
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}
}
public class HappyNumberUnitTest {
@Test
void whenUsingIsHappyNumber_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumber(7));
assertTrue(HappyNumberDecider.isHappyNumber(10));
assertTrue(HappyNumberDecider.isHappyNumber(13));
assertTrue(HappyNumberDecider.isHappyNumber(19));
assertTrue(HappyNumberDecider.isHappyNumber(23));
assertFalse(HappyNumberDecider.isHappyNumber(4));
assertFalse(HappyNumberDecider.isHappyNumber(6));
assertFalse(HappyNumberDecider.isHappyNumber(11));
assertFalse(HappyNumberDecider.isHappyNumber(15));
assertFalse(HappyNumberDecider.isHappyNumber(20));
}
@Test
void whenUsingIsHappyNumber2_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumberFloyd(7));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(10));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(13));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(19));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(23));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(4));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(6));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(11));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(15));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(20));
}
}
+1
View File
@@ -6,4 +6,5 @@ This module contains articles about Apache Kafka.
You can build the project from the command line using: *mvn clean install*, or in an IDE.
### Relevant Articles:
- [Commit Offsets in Kafka](https://www.baeldung.com/kafka-commit-offsets)
+1
View File
@@ -87,6 +87,7 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.version}</version>
</plugin>
</plugins>
</build>
@@ -13,4 +13,5 @@
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -2,3 +2,4 @@
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)
@@ -4,3 +4,4 @@ This module contains articles about the Java ArrayList collection
### Relevant Articles:
- [Create an ArrayList with Multiple Object Types](https://www.baeldung.com/java-arraylist-multiple-object-types)
- [Finding the Peak Elements of a List](https://www.baeldung.com/java-list-find-peak)
@@ -0,0 +1,49 @@
package com.baeldung.addtoimmutablelist;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
public class AddElementsToImmutableListUnitTest {
public static <T> List<T> appendAnElement(List<T> immutableList, T element) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.add(element);
return Collections.unmodifiableList(tmpList);
}
@SafeVarargs
public static <T> List<T> appendElements(List<T> immutableList, T... elements) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.addAll(Arrays.asList(elements));
return Collections.unmodifiableList(tmpList);
}
@Test
void whenCallingAppendAnElement_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected = List.of("A", "B", "C", "D", "E", "F");
List<String> result = appendAnElement(myList, "F");
assertThat(result).isEqualTo(expected)
.isUnmodifiable();
}
@Test
void whenCallingAppendElements_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected1 = List.of("A", "B", "C", "D", "E", "F");
List<String> result1 = appendElements(myList, "F");
assertThat(result1).isEqualTo(expected1)
.isUnmodifiable();
List<String> expected2 = List.of("A", "B", "C", "D", "E", "F", "G", "H", "I");
List<String> result2 = appendElements(myList, "F", "G", "H", "I");
assertThat(result2).isEqualTo(expected2)
.isUnmodifiable();
}
}
@@ -13,4 +13,5 @@ This module contains articles about Java collections
- [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)
- [Adding Elements to a Collection During Iteration](https://www.baeldung.com/java-add-elements-collection)
- More articles: [[next -->]](/core-java-modules/core-java-collections-2)
@@ -4,3 +4,4 @@
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)
- [CountDownLatch vs. Semaphore](https://www.baeldung.com/java-countdownlatch-vs-semaphore)
- [Callbacks in ListenableFuture and CompletableFuture](https://www.baeldung.com/java-callbacks-listenablefuture-completablefuture)
- [Guide to ExecutorService vs. CompletableFuture](https://www.baeldung.com/java-executorservice-vs-completablefuture)
@@ -5,3 +5,4 @@ This module contains articles about date operations in Java.
- [Calculate Number of Weekdays Between Two Dates in Java](https://www.baeldung.com/java-count-weekdays-between-two-dates)
- [Convert Long to Date in Java](https://www.baeldung.com/java-long-date-conversion)
- [Convert Date to Unix Timestamp in Java](https://www.baeldung.com/java-convert-date-unix-timestamp)
- [Checking if a Date Object Equals Yesterday](https://www.baeldung.com/java-date-check-yesterday)
@@ -0,0 +1,73 @@
package com.baeldung.usinggzipInputstream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import static java.util.stream.Collectors.toList;
public class Main {
static String filePath = Objects.requireNonNull(Main.class.getClassLoader().getResource("myFile.gz")).getFile();
public static void main(String[] args) throws IOException {
// Test readGZipFile method
List<String> fileContents = readGZipFile(filePath);
System.out.println("Contents of GZIP file:");
fileContents.forEach(System.out::println);
// Test findInZipFile method
String searchTerm = "Line 1 content";
List<String> foundLines = findInZipFile(filePath, searchTerm);
System.out.println("Lines containing '" + searchTerm + "' in GZIP file:");
foundLines.forEach(System.out::println);
// Test useContentsOfZipFile method
System.out.println("Using contents of GZIP file with consumer:");
useContentsOfZipFile(filePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(System.out::println);
});
}
public static List<String> readGZipFile(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
public static List<String> findInZipFile(String filePath, String toFind) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
return bufferedReader.lines().filter(line -> line.contains(toFind)).collect(toList());
}
}
public static void useContentsOfZipFile(String filePath, Consumer<Stream<String>> consumer) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
consumer.accept(bufferedReader.lines());
}
}
}
@@ -0,0 +1,50 @@
package com.baeldung.usinggzipInputstream;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class ReadingGZIPUsingGZIPInputStreamUnitTest {
String testFilePath = Objects.requireNonNull(ReadingGZIPUsingGZIPInputStreamUnitTest.class.getClassLoader().getResource("myFile.gz")).getFile();
List<String> expectedFilteredLines = Arrays.asList("Line 1 content", "Line 2 content", "Line 3 content");
@Test
void givenGZFile_whenUsingGZIPInputStream_thenReadLines() throws IOException {
try (Stream<String> lines = Main.readGZipFile(testFilePath).stream()) {
List<String> result = lines
.filter(expectedFilteredLines::contains)
.collect(Collectors.toList());
assertEquals(expectedFilteredLines, result);
}
}
@Test
void givenGZFile_whenUsingtestFindInZipFile_thenReadLines() throws IOException {
String toFind = "Line 1 content";
List<String> result = Main.findInZipFile(testFilePath, toFind);
assertEquals("Line 1 content", result.get(0));
}
@Test
void givenGZFile_whenUsingContentsOfZipFile_thenReadLines() throws IOException {
AtomicInteger count = new AtomicInteger(0);
Main.useContentsOfZipFile(testFilePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(line -> count.incrementAndGet());
});
assertEquals(3, count.get());
}
}
@@ -96,4 +96,5 @@
<properties>
<junit-jupiter-version>5.9.3</junit-jupiter-version>
</properties>
</project>
</project>
@@ -0,0 +1,39 @@
package com.baeldung.inputstreamreader;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class InputStreamReaderUnitTest {
@Test
public void givenAStringWrittenToAFile_whenReadByInputStreamReader_thenShouldMatchWhenRead(@TempDir Path tempDir) throws IOException {
String sampleTxt = "Good day. This is just a test. Good bye.";
Path sampleOut = tempDir.resolve("sample-out.txt");
List<String> lines = Arrays.asList(sampleTxt);
Files.write(sampleOut, lines);
String absolutePath = String.valueOf(sampleOut.toAbsolutePath());
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(absolutePath), StandardCharsets.UTF_8)) {
boolean isMatched = false;
int b;
StringBuilder sb = new StringBuilder();
while ((b = reader.read()) != -1) {
sb.append((char) b);
if (sb.toString().contains(sampleTxt)) {
isMatched = true;
break;
}
}
assertThat(isMatched).isTrue();
}
}
}
@@ -1,3 +1,4 @@
=========
### Relevant articles:
- [Calculate Percentiles in Java](https://www.baeldung.com/java-compute-percentiles)
@@ -0,0 +1,26 @@
package com.baeldung.constructorversussettermethod;
public class Product {
private String name;
private double price;
private String category;
public Product(String name, double price, String category) {
this.name = name;
this.price = price;
this.category = category;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.constructorversussettermethod;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
if (username.matches("[a-zA-Z0-9_]+")) {
this.username = username;
} else {
throw new IllegalArgumentException("Invalid username format");
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if (password.length() >= 8) {
this.password = password;
} else {
throw new IllegalArgumentException("Password must be at least 8 characters long");
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.constructorversussettermethod;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ConstructorsVersusSetterMethodsUnitTest {
@Test
public void givenNewUser_whenSettingUsername_thenUsernameIsSet() {
User user = new User();
user.setUsername("john_doe");
assertEquals("john_doe", user.getUsername());
}
@Test
public void givenNewUser_whenSettingPassword_thenPasswordIsSet() {
User user = new User();
user.setPassword("strongPassword123");
assertEquals("strongPassword123", user.getPassword());
}
@Test
public void givenProductDetails_whenCreatingProductWithConstructor_thenProductHasCorrectAttributes() {
Product product = new Product("Smartphone", 599.99, "Electronics");
assertEquals("Smartphone", product.getName());
assertEquals(599.99, product.getPrice(), 0.001);
assertEquals("Electronics", product.getCategory());
}
}
@@ -0,0 +1,14 @@
package com.baeldung.statementsbeforesuper;
class Child extends Parent {
Child() {
super(); // Or super(10); Correct placements
System.out.println("Child constructor");
additionalInitialization();
// super(); Compilation error: Constructor call must be the first statement in a constructor
}
private void additionalInitialization() {
System.out.println("Additional initialization in Child");
}
}
@@ -0,0 +1,11 @@
package com.baeldung.statementsbeforesuper;
public class Parent {
public Parent(int id) {
System.out.println("Parametrized Parent constructor");
}
public Parent() {
System.out.println("Parent constructor");
}
}
@@ -12,3 +12,4 @@ This module contains articles about Java operators
- [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan)
- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon)
- [Convert Infix to Postfix Expressions in Java](https://www.baeldung.com/java-convert-infix-to-postfix-expressions)
- [Representation of Integers at a Bit Level in Java](https://www.baeldung.com/java-integer-bit-representation)
@@ -6,7 +6,7 @@ import java.io.IOException;
import org.junit.Test;
public class UrlCheckerUnitTest {
public class UrlCheckerIntegrationTest {
@Test
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
@@ -18,7 +18,7 @@ public class UrlCheckerUnitTest {
@Test
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/xyz");
assertEquals(404, responseCode);
}
@@ -32,7 +32,7 @@ public class UrlCheckerUnitTest {
@Test
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
UrlChecker tester = new UrlChecker();
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
int responseCode = tester.getResponseCodeForURL("http://www.example.com/xyz");
assertEquals(404, responseCode);
}
@@ -8,4 +8,5 @@
- [Normalize a URL in Java](https://www.baeldung.com/java-url-normalization)
- [Translating Space Characters in URLEncoder](https://www.baeldung.com/java-urlencoder-translate-space-characters)
- [Creating a Custom URL Connection](https://www.baeldung.com/java-custom-url-connection)
- [[<-- Prev]](/core-java-modules/core-java-networking-3)
- [Obtaining the Last Path Segment of a URI in Java](https://www.baeldung.com/java-uri-get-last-path-segment)
- [[<-- Prev]](/core-java-modules/core-java-networking-3)
@@ -13,4 +13,5 @@ This module contains articles about numbers in Java.
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
- [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple)
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
- [RGB Representation as an Integer in Java](https://www.baeldung.com/java-rgb-color-representation)
- More articles: [[<-- prev]](../core-java-numbers) [[next -->]](../core-java-numbers-3)
@@ -49,7 +49,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@@ -73,6 +73,7 @@
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
<jacoco-maven-plugin.version>0.8.11</jacoco-maven-plugin.version>
</properties>
</project>
@@ -49,7 +49,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@@ -73,6 +73,7 @@
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
<jacoco-maven-plugin.version>0.8.11</jacoco-maven-plugin.version>
</properties>
</project>
@@ -0,0 +1,143 @@
package com.baeldung.streams.mapstreamtomap;
import static java.lang.Math.max;
import static java.util.stream.Collectors.flatMapping;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.reducing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class MapStreamToMapUnitTest {
Map<String, Integer> playerMap1 = new HashMap<String, Integer>() {{
put("Kai", 92);
put("Liam", 100);
}};
Map<String, Integer> playerMap2 = new HashMap<String, Integer>() {{
put("Eric", 42);
put("Kevin", 77);
}};
Map<String, Integer> playerMap3 = new HashMap<String, Integer>() {{
put("Saajan", 35);
}};
Map<String, Integer> playerMap4 = new HashMap<String, Integer>() {{
put("Kai", 76);
}};
Map<String, Integer> playerMap5 = new HashMap<String, Integer>() {{
put("Kai", null);
put("Jerry", null);
}};
@Test
void givenMapsStream_whenUsingFlatMapAndToMap_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92);
put("Eric", 42);
put("Kevin", 77);
}};
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
assertEquals(expectedMap, mergedMap);
}
@Test
void givenMapsWithDuplicateKeys_whenUsingFlatMapAndToMap_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 76 and 92
put("Eric", 42);
put("Kevin", 77);
}};
assertThrows(IllegalStateException.class, () -> Stream.of(playerMap1, playerMap2, playerMap3, playerMap4)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), "Duplicate key Kai (attempted merging values 92 and 76)");
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3, playerMap4)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::max));
assertEquals(expectedMap, mergedMap);
}
private Integer maxInteger(Integer int1, Integer int2) {
if (int1 == null) {
return int2;
}
if (int2 == null) {
return int1;
}
return max(int1, int2);
}
@Test
void givenMapsWithDuplicateKeysAndNullValues_whenUsingFlatMapWithForEach_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 92, 76, and null
put("Eric", 42);
put("Kevin", 77);
put("Jerry", null);
}};
assertThrows(NullPointerException.class, () -> Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::max)));
Map<String, Integer> mergedMap = new HashMap<>();
Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(map -> map.entrySet()
.stream())
.forEach(entry -> {
String k = entry.getKey();
Integer v = entry.getValue();
if (mergedMap.containsKey(k)) {
mergedMap.put(k, maxInteger(mergedMap.get(k), v));
} else {
mergedMap.put(k, v);
}
});
assertEquals(expectedMap, mergedMap);
}
@Test
void givenMapsWithDuplicateKeysAndNullValues_whenUsingReduce_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 92, 76, and null
put("Eric", 42);
put("Kevin", 77);
put("Jerry", null);
}};
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(x -> x.entrySet()
.stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, reducing(null, this::maxInteger))));
assertEquals(expectedMap, mergedMap);
}
}

Some files were not shown because too many files have changed in this diff Show More