1+ package com .baeldung .interpreter ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .Collection ;
5+ import java .util .HashMap ;
6+ import java .util .List ;
7+ import java .util .Map ;
8+ import java .util .function .Function ;
9+ import java .util .function .Predicate ;
10+ import java .util .stream .Collectors ;
11+ import java .util .stream .Stream ;
12+
13+ class Context {
14+
15+ private static Map <String , List <Row >> tables = new HashMap <>();
16+
17+ static {
18+ List <Row > list = new ArrayList <>();
19+ list .add (new Row ("John" , "Doe" ));
20+ list .add (new Row ("Jan" , "Kowalski" ));
21+ list .add (new Row ("Dominic" , "Doom" ));
22+
23+ tables .put ("people" , list );
24+ }
25+
26+ private String table ;
27+ private String column ;
28+
29+ /**
30+ * Index of column to be shown in result.
31+ * Calculated in {@link #setColumnMapper()}
32+ */
33+ private int colIndex = -1 ;
34+
35+ /**
36+ * Default setup, used for clearing the context for next queries.
37+ * See {@link Context#clear()}
38+ */
39+ private static final Predicate <String > matchAnyString = s -> s .length () > 0 ;
40+ private static final Function <String , Stream <? extends String >> matchAllColumns = Stream ::of ;
41+ /**
42+ * Varies based on setup in subclasses of {@link Expression}
43+ */
44+ private Predicate <String > whereFilter = matchAnyString ;
45+ private Function <String , Stream <? extends String >> columnMapper = matchAllColumns ;
46+
47+ void setColumn (String column ) {
48+ this .column = column ;
49+ setColumnMapper ();
50+ }
51+
52+ void setTable (String table ) {
53+ this .table = table ;
54+ }
55+
56+ void setFilter (Predicate <String > filter ) {
57+ whereFilter = filter ;
58+ }
59+
60+ /**
61+ * Clears the context to defaults.
62+ * No filters, match all columns.
63+ */
64+ void clear () {
65+ column = "" ;
66+ columnMapper = matchAllColumns ;
67+ whereFilter = matchAnyString ;
68+ }
69+
70+ List <String > search () {
71+
72+ List <String > result = tables .entrySet ()
73+ .stream ()
74+ .filter (entry -> entry .getKey ().equalsIgnoreCase (table ))
75+ .flatMap (entry -> Stream .of (entry .getValue ()))
76+ .flatMap (Collection ::stream )
77+ .map (Row ::toString )
78+ .flatMap (columnMapper )
79+ .filter (whereFilter )
80+ .collect (Collectors .toList ());
81+
82+ clear ();
83+
84+ return result ;
85+ }
86+
87+ /**
88+ * Sets column mapper based on {@link #column} attribute.
89+ * Note: If column is unknown, will remain to look for all columns.
90+ */
91+ private void setColumnMapper () {
92+ switch (column ) {
93+ case "*" :
94+ colIndex = -1 ;
95+ break ;
96+ case "name" :
97+ colIndex = 0 ;
98+ break ;
99+ case "surname" :
100+ colIndex = 1 ;
101+ break ;
102+ }
103+ if (colIndex != -1 ) {
104+ columnMapper = s -> Stream .of (s .split (" " )[colIndex ]);
105+ }
106+ }
107+ }
0 commit comments