1+ package com .rampatra .misc ;
2+
3+ import java .util .Arrays ;
4+ import java .util .HashMap ;
5+ import java .util .List ;
6+ import java .util .Map ;
7+ import java .util .stream .Collectors ;
8+
9+ /**
10+ * A rudimentary example explaining the concept of Map/Reduce paradigm. The question is, provided a list of Person
11+ * objects from various countries, compute the total population in each country.
12+ *
13+ * @author rampatra
14+ * @since 2019-02-26
15+ */
16+ public class MapReduce {
17+
18+ private static class Person {
19+ String name ;
20+ int age ;
21+ String country ;
22+
23+ Person (String country ) {
24+ this .country = country ;
25+ }
26+ }
27+
28+ /**
29+ * The mapper function will take all the data and output only the information which we need, and in this
30+ * case, it is just the country name to which a person belongs.
31+ *
32+ * @param personList a list of all persons
33+ * @return a list of country names
34+ */
35+ private static List <String > mapper (List <Person > personList ) {
36+ return personList .stream ().map (person -> person .country ).collect (Collectors .toList ());
37+ }
38+
39+ /**
40+ * The reducer function will take all the useful information from the mapper function and then compute the result
41+ * we need. In this case, it is to count the number of persons in each country.
42+ *
43+ * @param countryNamesOfAllPersons a list of country names taken out of all {@code Person} objects
44+ * @return a map containing country names as the keys and their resp. population as values
45+ */
46+ private static Map <String , Integer > reducer (List <String > countryNamesOfAllPersons ) {
47+ Map <String , Integer > countryToPopulationMap = new HashMap <>();
48+
49+ countryNamesOfAllPersons .forEach (countryName -> {
50+ countryToPopulationMap .computeIfPresent (countryName , (country , population ) -> population + 1 );
51+ countryToPopulationMap .computeIfAbsent (countryName , country -> countryToPopulationMap .put (country , 1 ));
52+ });
53+
54+ return countryToPopulationMap ;
55+ }
56+
57+ /**
58+ * Just to print the output.
59+ *
60+ * @param countryToPopulationMap a map containing country names as the keys and their resp. population as values
61+ */
62+ private static void printPopulation (Map <String , Integer > countryToPopulationMap ) {
63+ countryToPopulationMap .forEach ((k , v ) -> System .out .println (k + ": " + v ));
64+ }
65+
66+ public static void main (String [] args ) {
67+
68+ Person [] persons = new Person []{new Person ("India" ), new Person ("Ireland" ),
69+ new Person ("Sweden" ), new Person ("United States" ), new Person ("India" ),
70+ new Person ("Ireland" ), new Person ("India" )};
71+
72+ printPopulation (reducer (mapper (Arrays .asList (persons ))));
73+ }
74+ }
0 commit comments