Repository: TheAlgorithms/Java
Pull request #6348 (2025-07-06 17:55:45)

refactor: improve code and test coverage for `MapReduce` example
- Renamed `mapreduce` method to `countWordFrequencies` for improved clarity and accuracy
- Improved internal word splitting by using `trim()` and `split("\\s+")` for better whitespace handling
- Replaced manual string building with `Collectors.joining(",")` for cleaner reduce phase logic
- Added parameterized tests

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6348?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 74.56%. Comparing base [(`350f149`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/350f1496573c218f1d3796ed80811d4f46060125?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`7f5900d`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7f5900d855f497a2c537a5d7422abfcdeaea90a6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #6348      +/-   ##
============================================
- Coverage     74.56%   74.56%   -0.01%     
  Complexity     5451     5451              
============================================
  Files           682      682              
  Lines         19036    19032       -4     
  Branches       3690     3689       -1     
============================================
- Hits          14194    14191       -3     
  Misses         4277     4277              
+ Partials        565      564       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/6348?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary> :rocket: New features to boost your workflow: </summary>

- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
</details>

Patch:
diff --git a/src/main/java/com/thealgorithms/misc/MapReduce.java b/src/main/java/com/thealgorithms/misc/MapReduce.java
index c0769573..d98b2ee2 100644
--- a/src/main/java/com/thealgorithms/misc/MapReduce.java
+++ b/src/main/java/com/thealgorithms/misc/MapReduce.java
@@ -7,35 +7,34 @@ import java.util.Map;
 import java.util.function.Function;
 import java.util.stream.Collectors;
 
-/*
-* MapReduce is a programming model for processing and generating large data sets with a parallel,
-distributed algorithm on a cluster.
-* It has two main steps: the Map step, where the data is divided into smaller chunks and processed in parallel,
-and the Reduce step, where the results from the Map step are combined to produce the final output.
-* Wikipedia link : https://en.wikipedia.org/wiki/MapReduce
-*/
-
+/**
+ * MapReduce is a programming model for processing and generating large data sets
+ * using a parallel, distributed algorithm on a cluster.
+ * It consists of two main phases:
+ * - Map: the input data is split into smaller chunks and processed in parallel.
+ * - Reduce: the results from the Map phase are aggregated to produce the final output.
+ *
+ * See also: https://en.wikipedia.org/wiki/MapReduce
+ */
 public final class MapReduce {
+
     private MapReduce() {
     }
-    /*
-     *Counting all the words frequency within a sentence.
-     */
-    public static String mapreduce(String sentence) {
-        List<String> wordList = Arrays.stream(sentence.split(" ")).toList();
 
-        // Map step
-        Map<String, Long> wordCounts = wordList.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
-
-        // Reduce step
-        StringBuilder result = new StringBuilder();
-        wordCounts.forEach((word, count) -> result.append(word).append(": ").append(count).append(","));
+    /**
+     * Counts the frequency of each word in a given sentence using a simple MapReduce-style approach.
+     *
+     * @param sentence the input sentence
+     * @return a string representing word frequencies in the format "word: count,word: count,..."
+     */
+    public static String countWordFrequencies(String sentence) {
+        // Map phase: split the sentence into words
+        List<String> words = Arrays.asList(sentence.trim().split("\\s+"));
 
-        // Removing the last ',' if it exists
-        if (!result.isEmpty()) {
-            result.setLength(result.length() - 1);
-        }
+        // Group and count occurrences of each word, maintain insertion order
+        Map<String, Long> wordCounts = words.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
 
-        return result.toString();
+        // Reduce phase: format the result
+        return wordCounts.entrySet().stream().map(entry -> entry.getKey() + ": " + entry.getValue()).collect(Collectors.joining(","));
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/misc/MapReduceTest.java b/src/test/java/com/thealgorithms/misc/MapReduceTest.java
index c79c4070..748dd0a5 100644
--- a/src/test/java/com/thealgorithms/misc/MapReduceTest.java
+++ b/src/test/java/com/thealgorithms/misc/MapReduceTest.java
@@ -2,22 +2,14 @@ package com.thealgorithms.misc;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 
-import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 
 public class MapReduceTest {
-    @Test
-    public void testMapReduceWithSingleWordSentence() {
-        String oneWordSentence = "Hactober";
-        String result = MapReduce.mapreduce(oneWordSentence);
-
-        assertEquals("Hactober: 1", result);
-    }
-
-    @Test
-    public void testMapReduceWithMultipleWordSentence() {
-        String multipleWordSentence = "I Love Love HactoberFest";
-        String result = MapReduce.mapreduce(multipleWordSentence);
-
-        assertEquals("I: 1,Love: 2,HactoberFest: 1", result);
+    @ParameterizedTest
+    @CsvSource({"'hello world', 'hello: 1,world: 1'", "'one one two', 'one: 2,two: 1'", "'a a a a', 'a: 4'", "'  spaced  out  ', 'spaced: 1,out: 1'"})
+    void testCountWordFrequencies(String input, String expected) {
+        String result = MapReduce.countWordFrequencies(input);
+        assertEquals(expected, result);
     }
 }