-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapReduceComposite.java
106 lines (87 loc) · 2.62 KB
/
MapReduceComposite.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//Copied and solved as the hackerrank task
import java.util.*;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
class MapReduceComposite
{
private LinkedHashMap intermediate;
private JSONObject finalResult = new JSONObject();
private int resultCount;
MapReduce()
{
resultCount=0;
finalResult = new JSONObject();
intermediate=new LinkedHashMap();
}
JSONObject execute(JSONObject inputdata)
{
for(int i=0;i<inputdata.size();i++)
{
JSONObject record=(JSONObject)inputdata.get(i);
mapper(record);
}
Iterator it = intermediate.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
reducer((String) pair.getKey(), (ArrayList)pair.getValue());
it.remove();
}
return finalResult;
}
private void emit(LinkedHashMap obj)
{
finalResult.put(resultCount++,obj);
}
private <T> void reducer(T key, ArrayList value)
{
LinkedHashMap obj=new LinkedHashMap();
obj.put("key",key);
double population=0;
//??? Complete this line
obj.put("value", Math.round(population));
emit(obj);
}
private void mapper(JSONObject record)
{
String state=(String)record.get("key");
double population=Double.parseDouble((String)record.get("value"));
//Complete the line below
emitIntermediate(?,?);
}
private <T1,T2> void emitIntermediate(T1 key, T2 value)
{
if(!intermediate.containsKey(key))
intermediate.put(key,new ArrayList());
ArrayList temp=(ArrayList)intermediate.get(key);
temp.add(value);
intermediate.put(key,temp);
}
}
public class Main
{
public static void main(String []argh)
{
JSONObject inputdata= new JSONObject();
Scanner sc=new Scanner(System.in);
int linecount=0;
while(sc.hasNext())
{
String line=sc.nextLine();
String []temp=line.split("\t");
Map obj=new JSONObject();
obj.put("key",temp[0]+","+temp[1]);
obj.put("value",temp[3]);
inputdata.put(linecount++,obj);
}
MapReduce mapred= new MapReduce();
JSONObject result=mapred.execute(inputdata);
for(int i=0;i<result.size();i++)
{
LinkedHashMap record=(LinkedHashMap)result.get(i);
String key=(String)record.get("key");
long value=(long)record.get("value");
System.out.println ("{\"key\":\""+key+"\",\"value\":"+value+"}");
}
}
}