forked from paulnguyen/code
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueryTool.java
More file actions
87 lines (67 loc) · 2.09 KB
/
QueryTool.java
File metadata and controls
87 lines (67 loc) · 2.09 KB
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
import java.util.ArrayList;
import java.util.UUID;
public class QueryTool {
interface Filter {
boolean operation(String item);
}
interface Reducer {
int operation(int item, int accumulator);
}
public ArrayList<String> query(String query)
{
ArrayList<String> results = new ArrayList<String>() ;
// setup a sample list
results.add( "1") ;
results.add( "2") ;
results.add( "3") ;
results.add( "4") ;
results.add( "5") ;
results.add( "6") ;
results.add( "7") ;
results.add( "8") ;
results.add( "9") ;
results.add( "10") ;
// return results
return results ;
}
public ArrayList<String> map(ArrayList<String> rs, Filter f)
{
ArrayList<String> out = new ArrayList<>() ;
rs.forEach( e -> {
String key = UUID.randomUUID().toString();
if ( f.operation(e) ) {
out.add( key + " => " + e ) ;
}
}
) ;
return out ;
}
public int reduce(ArrayList<String> inputList, Reducer r)
{
int sum = 0 ;
for (String item: inputList) {
String[] parts = item.split("=> ");
int val = Integer.parseInt(parts[1]);
sum = r.operation( val, sum ) ;
}
return sum ;
}
public static void main(String[] args) {
QueryTool q = new QueryTool() ;
ArrayList<String> dataset = q.query( "select * from test" ) ;
// filters functions
Filter evens = (a) -> ((Integer.parseInt(a)) % 2) == 0;
Filter odds = (a) -> ((Integer.parseInt(a)) % 2) != 0;
// Java's built-in iterator
ArrayList<String> mapset = q.map(dataset, evens) ;
System.out.println( "\nMap..." ) ;
mapset.forEach( e -> System.out.println(e)) ;
// reducer functions
Reducer sumfunc = (i,a) -> { return (a += i) ; } ;
Reducer sumdiv2 = (i,a) -> { return (a += (i/2)) ; } ;
// Reduce
System.out.println( "\nReduce..." ) ;
int sum = q.reduce(mapset, sumdiv2 ) ;
System.out.println( sum ) ;
}
}