Skip to content

Commit a4711d6

Browse files
authored
Added MapReduce Algorithm in Misc Folder. (TheAlgorithms#4828)
* Added MapReduce Algorithm in Misc Folder. * Did formatting correctly * Removed main function and added MapReduceTest * format the code
1 parent 9dae389 commit a4711d6

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.misc;
2+
3+
import java.util.Arrays;
4+
import java.util.LinkedHashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
import java.util.function.Function;
8+
import java.util.stream.Collectors;
9+
10+
/*
11+
* MapReduce is a programming model for processing and generating large data sets with a parallel,
12+
distributed algorithm on a cluster.
13+
* It has two main steps: the Map step, where the data is divided into smaller chunks and processed in parallel,
14+
and the Reduce step, where the results from the Map step are combined to produce the final output.
15+
* Wikipedia link : https://en.wikipedia.org/wiki/MapReduce
16+
*/
17+
18+
public class MapReduce {
19+
/*
20+
*Counting all the words frequency within a sentence.
21+
*/
22+
public static String mapreduce(String sentence) {
23+
List<String> wordList = Arrays.stream(sentence.split(" ")).toList();
24+
25+
// Map step
26+
Map<String, Long> wordCounts = wordList.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
27+
28+
// Reduce step
29+
StringBuilder result = new StringBuilder();
30+
wordCounts.forEach((word, count) -> result.append(word).append(": ").append(count).append(","));
31+
32+
// Removing the last ',' if it exists
33+
if (!result.isEmpty()) {
34+
result.setLength(result.length() - 1);
35+
}
36+
37+
return result.toString();
38+
}
39+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.misc;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class MapReduceTest {
8+
@Test
9+
public void testMapReduceWithSingleWordSentence() {
10+
String oneWordSentence = "Hactober";
11+
String result = MapReduce.mapreduce(oneWordSentence);
12+
13+
assertEquals("Hactober: 1", result);
14+
}
15+
16+
@Test
17+
public void testMapReduceWithMultipleWordSentence() {
18+
String multipleWordSentence = "I Love Love HactoberFest";
19+
String result = MapReduce.mapreduce(multipleWordSentence);
20+
21+
assertEquals("I: 1,Love: 2,HactoberFest: 1", result);
22+
}
23+
}

0 commit comments

Comments
 (0)