-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrays.html
executable file
·419 lines (408 loc) · 38.5 KB
/
arrays.html
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- Generated by Apache Maven Doxia Site Renderer 1.3 at May 19, 2012 -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>op4j: bending the Java spoon - Working with arrays</title>
<style type="text/css" media="all">
@import url("./css/maven-base.css");
@import url("./css/maven-theme.css");
@import url("./css/site.css");
</style>
<link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
<meta name="Date-Revision-yyyymmdd" content="20120519" />
<meta http-equiv="Content-Language" content="en" />
</head>
<body class="composite">
<div id="banner">
<a href="./" id="bannerLeft">
<img src="images/op4j_logo.png" alt="op4j: bending the Java spoon" />
</a>
<div class="clear">
<hr/>
</div>
</div>
<div id="breadcrumbs">
<div class="xleft">
<span id="publishDate">Last Published: 19 May 2012</span>
| <span id="projectVersion">Version: 1.2</span>
</div>
<div class="xright"> <a href="index.html" title="Main">Main</a>
|
<a href="download.html" title="Download">Download</a>
|
<a href="https://www.bendingthejavaspoon.com" class="externalLink" title="Example Recipes Blog">Example Recipes Blog</a>
|
<a href="https://github.com/op4j/op4j.github.com/issues" class="externalLink" title="Issue Tracking">Issue Tracking</a>
|
<a href="apidocs/index.html" title="Javadoc">Javadoc</a>
|
<a href="https://github.com/op4j" class="externalLink" title="Github Project Page">Github Project Page</a>
</div>
<div class="clear">
<hr/>
</div>
</div>
<div id="leftColumn">
<div id="navcolumn">
<h5>The op4j Project</h5>
<ul>
<li class="none">
<a href="index.html" title="· Main">· Main</a>
</li>
<li class="none">
<a href="download.html" title="· Download">· Download</a>
</li>
<li class="none">
<a href="maveninfo.html" title="· Maven Info">· Maven Info</a>
</li>
<li class="none">
<a href="dependencies.html" title="· Dependencies">· Dependencies</a>
</li>
<li class="none">
<a href="https://github.com/op4j" class="externalLink" title="· Github Repository">· Github Repository</a>
</li>
<li class="none">
<a href="https://www.bendingthejavaspoon.com" class="externalLink" title="· Example Recipes">· Example Recipes</a>
</li>
<li class="none">
<a href="https://github.com/op4j/op4j.github.com/issues" class="externalLink" title="· Issue Tracking">· Issue Tracking</a>
</li>
<li class="expanded">
<a href="#" title="· Documentation">· Documentation</a>
<ul>
<li class="none">
<a href="basics.html" title="· The Basics">· The Basics</a>
</li>
<li class="expanded">
<a href="#" title="· Working with...">· Working with...</a>
<ul>
<li class="none">
<strong>· Arrays</strong>
</li>
<li class="none">
<a href="lists.html" title="· Lists">· Lists</a>
</li>
<li class="none">
<a href="maps.html" title="· Maps">· Maps</a>
</li>
<li class="none">
<a href="sets.html" title="· Sets">· Sets</a>
</li>
<li class="none">
<a href="generic.html" title="· Any object (generic)">· Any object (generic)</a>
</li>
</ul>
</li>
<li class="expanded">
<a href="#" title="· Functions">· Functions</a>
<ul>
<li class="none">
<a href="functions.html" title="· About Functions">· About Functions</a>
</li>
<li class="none">
<a href="call.html" title="· Call">· Call</a>
</li>
<li class="none">
<a href="get.html" title="· Get">· Get</a>
</li>
<li class="none">
<a href="fnfunc.html" title="· FnFunc">· FnFunc</a>
</li>
<li class="none">
<a href="fnboolean.html" title="· FnBoolean">· FnBoolean</a>
</li>
<li class="none">
<a href="fncalendar.html" title="· FnCalendar">· FnCalendar</a>
</li>
<li class="none">
<a href="fndate.html" title="· FnDate">· FnDate</a>
</li>
<li class="none">
<a href="fnobject.html" title="· FnObject">· FnObject</a>
</li>
<li class="none">
<a href="fnstring.html" title="· FnString">· FnString</a>
</li>
<li class="expanded">
<a href="#" title="· Numbers">· Numbers</a>
<ul>
<li class="none">
<a href="fnnumber.html" title="· FnNumber">· FnNumber</a>
</li>
<li class="none">
<a href="fnbigdecimal.html" title="· FnBigDecimal">· FnBigDecimal</a>
</li>
<li class="none">
<a href="fnbiginteger.html" title="· FnBigInteger">· FnBigInteger</a>
</li>
<li class="none">
<a href="fninteger.html" title="· FnInteger">· FnInteger</a>
</li>
<li class="none">
<a href="fnlong.html" title="· FnLong">· FnLong</a>
</li>
<li class="none">
<a href="fnfloat.html" title="· FnFloat">· FnFloat</a>
</li>
<li class="none">
<a href="fndouble.html" title="· FnDouble">· FnDouble</a>
</li>
<li class="none">
<a href="fndouble.html" title="· FnShort">· FnShort</a>
</li>
</ul>
</li>
<li class="expanded">
<a href="#" title="· Structures">· Structures</a>
<ul>
<li class="none">
<a href="fnarray.html" title="· FnArray">· FnArray</a>
</li>
<li class="none">
<a href="fnlist.html" title="· FnList">· FnList</a>
</li>
<li class="none">
<a href="fnmap.html" title="· FnMap">· FnMap</a>
</li>
<li class="none">
<a href="fnset.html" title="· FnSet">· FnSet</a>
</li>
<li class="none">
<a href="fntuple.html" title="· FnTuple">· FnTuple</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="none">
<a href="apidocs/op4j/index.html" title="· Javadoc">· Javadoc</a>
</li>
<li class="none">
<a href="faq.html" title="· FAQ">· FAQ</a>
</li>
</ul>
</li>
<li class="none">
<a href="license.html" title="· License">· License</a>
</li>
<li class="none">
<a href="team.html" title="· Team">· Team</a>
</li>
</ul>
<ul>
<li class="collapsed">
<a href="ognl-about.html" title="· op4j-ognl">· op4j-ognl</a>
</li>
<li class="collapsed">
<a href="jodatime-about.html" title="· op4j-jodatime">· op4j-jodatime</a>
</li>
</ul>
<a href="https://maven.apache.org" title="Built with Maven 2" class="poweredBy">
<img class="poweredBy" alt="Built with Maven 2" src="https://maven.apache.org/images/logos/maven-feather.png" />
</a>
</div>
</div>
<div id="bodyColumn">
<div id="contentBox">
<div class="section"><h2>Working with arrays<a name="Working_with_arrays"></a></h2><p>This page explains how op4j can deal with array objects.</p><p>Array input objects are considered immutable, so they will not be changed when used in an op4j expression and a new array will always be returned when executing <tt>get()</tt>.</p><p>This, however, does not apply to the input array's element objects, which could be changed if you executed on them any functions which might change their state instead of substituting them for new elements.</p><ul><li><a href="#a1">Creating array expressions</a></li><li><a href="#a2">Converting to lists, sets or maps</a></li><li><a href="#a3">Iterating</a></li><li><a href="#a4">Modifying</a></li><li><a href="#a5">Executing functions</a></li><li><a href="#a6">Mapping functions</a></li><li><a href="#a7">Selecting (conditional code)</a></li><li><a href="#a8">Replacing</a></li><li><a href="#a9">Removing duplicates</a></li><li><a href="#a10">Sorting</a></li><li><a href="#a11">Boolean conditions: all, any</a></li><li><a href="#a12">Reversing</a></li></ul><div class="section"><h3><a name="a1">1</a>. Creating array expressions<a name="a1._Creating_array_expressions"></a></h3><div class="section"><h4>Operation expressions<a name="Operation_expressions"></a></h4><p>The creation of operation expressions on arrays in op4j is a little bit different (and a little bit more complex) than it is for creating any other kind of operation expression.</p><p>This is because, when dealing with structures (arrays, lists, maps or sets), op4j needs to be able to internally create new instances of those structures. And while creating an instance of <tt>List<String></tt> or <tt>List<Integer></tt> is just a matter of instantiating the <tt>java.util.ArrayList</tt> class (independently of its type parameters or <i>generics</i>), for instantiating an array the <i>actual array class</i> is needed, and creating an instance of <tt>String[]</tt> is different from creating an instance of <tt>Integer[]</tt>.</p><p>Although Java makes this in fact a little bit more complex than what is explained here, this is in general terms why <b>op4j needs a Type (javaRuntype Type) to be specified when creating operation expressions on arrays</b>. Specifically, it needs the type of the array elements (i.e. <tt>Type<String></tt> for a String[]).</p><div class="section"><h5>Specifying the array element type<a name="Specifying_the_array_element_type"></a></h5><p>This is then the basic way of creating an operation expression on an array:</p><div class="source"><pre>String[] array = ...;
Op.onArrayOf(Types.STRING, array)...
</pre></div></div><div class="section"><h5>Making it faster: the partial array operator<a name="Making_it_faster:_the_partial_array_operator"></a></h5><p>In order to make this faster, however, an abbreviated option is available: </p><div class="source"><pre>MyObject[] array = ...;
Op.on(array)...
</pre></div><p>...which looks like the creation of an operation expression for a list, a map, a set or any other object, but in fact on an array this will only give you a <b>partial operator</b>. An operator only able of executing some actions (for example, <tt>exec(...)</tt> or <tt>toList()</tt>) which do not involve instantiating a new array. For example, you will not be able to iterate (<tt>forEach()</tt>), but this will be valid:</p><div class="source"><pre>MyObject[] array = ...;
List<MyObject> list = Op.on(array).toList().get();
</pre></div><p>In order to convert a partial array operator into a full-featured array operator, a cast will be needed: </p><div class="source"><pre>MyObject[] array = ...;
Type<MyObject> myType = ...;
Op.on(array).asArrayOf(myType).forEach()...
</pre></div></div><div class="section"><h5>Making it even faster for known types<a name="Making_it_even_faster_for_known_types"></a></h5><p>There are some types, though, which are of everyday use, and for which op4j offers you the possibility of <b>obtaining a full-featured array operator without specifying the type</b>.</p><p>These types are:</p><ul><li><tt>String[]</tt></li><li><tt>Boolean[]</tt></li><li><tt>Character[]</tt></li><li>Numbers: <tt>Byte[]</tt>, <tt>Short[]</tt>, <tt>Integer[]</tt>, <tt>Long[]</tt>, <tt>Float[]</tt>, <tt>Double[]</tt>, <tt>BigInteger[]</tt>, <tt>BigDecimal[]</tt>.</li><li>Dates: <tt>Calendar[]</tt>, <tt>java.util.Date[]</tt>, <tt>java.sql.Date[]</tt>, <tt>Timestamp[]</tt>. </li></ul><p><b>For arrays of all these types, the abbreviated method of creating the operation expression returns a full-featured operator</b> just as if <tt>onArrayOf(...)</tt> had been executed instead:</p><div class="source"><pre>String[] array = ...;
Op.on(array).forEach()...
</pre></div><p>This code is therefore completely equivalent to:</p><div class="source"><pre>String[] array = ...;
Op.onArrayOf(Types.STRING, array).forEach()...
</pre></div></div><div class="section"><h5>Creating arrays from their elements<a name="Creating_arrays_from_their_elements"></a></h5><p>Array expressions can be created by directly specifying the array elements, like this:</p><div class="source"><pre>Op.onArrayFor("hello", "ola", "hola", "hallo", "ciao").forEach()...
</pre></div></div></div><div class="section"><h4>Function expressions<a name="Function_expressions"></a></h4><p>Function expressions are created as usual with other structures:</p><div class="source"><pre>// Create a function which receives a String[] variable as input
function = Fn.onArrayOf(Types.STRING)...get();
</pre></div></div></div><div class="section"><h3><a name="a2">2</a>. Converting to lists, sets or maps.<a name="a2._Converting_to_lists_sets_or_maps."></a></h3><div class="section"><h4>Lists<a name="Lists"></a></h4><p>For converting an array into a list:</p><div class="source"><pre>List<String> list = Op.on(array).toList().get();
</pre></div></div><div class="section"><h4>Sets<a name="Sets"></a></h4><p>For converting an array into a set:</p><div class="source"><pre>Set<String> set = Op.on(array).toSet().get();
</pre></div></div><div class="section"><h4>Maps<a name="Maps"></a></h4><div class="section"><h5>Using a Map Builder<a name="Using_a_Map_Builder"></a></h5><p>A Map Builder is an function which returns map entries (<tt>IFunction<T,Map.Entry<K,V>></tt>), usually created by extending the abstract class <tt>org.op4j.functions.MapBuilder</tt>, and which provides op4j with a way of creating a map entry from each of the array's elements.</p><p><tt>MapBuilder</tt> looks like this:</p><div class="source"><pre>public abstract class MapBuilder<T,K,V> implements IFunction<T,Map.Entry<K,V>> {
public abstract K buildKey(final T target);
public abstract V buildValue(final T target);
...
}
</pre></div><p>...and using it is very easy: </p><div class="source"><pre>MapBuilder<String,Integer,Calendar> mapBuilder = ...;
Map<Integer,Calendar> map = Op.on(array).toMap(mapBuilder).get();
</pre></div><div class="section"><h6>Grouping using a Map Builder<a name="Grouping_using_a_Map_Builder"></a></h6><p>If one or more values can have the same key, you should create a <i>grouped map</i>, like:</p><div class="source"><pre>MapBuilder<String,Integer,Calendar> mapBuilder = ...;
Map<Integer,Calendar[]> map = Op.on(array).toGroupMapOf(Types.CALENDAR, mapBuilder).get();
</pre></div></div></div><div class="section"><h5>Using two functions<a name="Using_two_functions"></a></h5><p>Instead of a <i>map builder</i> function, we could just use two functions instead, one for creating keys, and a different one for creating values:</p><div class="source"><pre>IFunction<String,Integer> keyFunction = ...;
IFunction<String,Calendar> valueFunction = ...;
Map<Integer,Calendar> map = Op.on(array).toMap(keyFunction, valueFunction).get();
</pre></div><div class="section"><h6>Grouping using two functions<a name="Grouping_using_two_functions"></a></h6><p>Again, if one or more values can have the same key, you should create a <i>grouped map</i>, like:</p><div class="source"><pre>IFunction<String,Integer> keyFunction = ...;
IFunction<String,Calendar> valueFunction = ...;
Map<Integer,Calendar[]> map = Op.on(array).toGroupMapOf(Types.CALENDAR, keyFunction, valueFunction).get();
</pre></div></div></div><div class="section"><h5>Zipping keys or values<a name="Zipping_keys_or_values"></a></h5><p>A Map can also be created from an array by zipping. Zipping means combining the elements in the array with other objects like this:</p><div class="source"><pre>// map = {{1="a"}, {2="b"}}
Map<Integer,String> map =
Op.onArrayFor(1,2).zipValues("a","b").get();
</pre></div><p>...using a collection...</p><div class="source"><pre>Collection<String> values = {"a", "b"};
// map = {{1="a"}, {2="b"}}
Map<Integer,String> map =
Op.onArrayFor(1,2).zipValuesFrom(values).get();
</pre></div><p>Or similarly:</p><div class="source"><pre>// map = {{"a"=1}, {"b"=2}}
Map<String,Integer> map =
Op.onArrayFor(1,2).zipKeys("a","b").get();
</pre></div><p>...using a collection...</p><div class="source"><pre>Collection<String> keys = {"a", "b"};
// map = {{"a"=1}, {"b"=2}}
Map<String,Integer> map =
Op.onArrayFor(1,2).zipKeysFrom(keys).get();
</pre></div><p>Alternatively, a function can be used for evaluating existing elements and obtaining keys or values:</p><div class="source"><pre>IFunction<Integer,String> valueEvaluatorFn = ...;
Map<Integer,String> map =
Op.onArrayFor(1,2).zipValuesBy(valueEvaluatorFn).get();
</pre></div><div class="source"><pre>IFunction<Integer,String> keyEvaluatorFn = ...;
Map<String,Integer> map =
Op.onArrayFor(1,2).zipKeysBy(keyEvaluatorFn).get();
</pre></div><div class="section"><h6>Zipping and Grouping<a name="Zipping_and_Grouping"></a></h6><p>Collisions (entries with the same key) can be avoided when zipping by using <i>grouping</i> actions:</p><div class="source"><pre>// mapOfArrays = {{1=["a","c"]}, {2=["b","d","e]}}
Map<Integer,String[]> mapOfArrays =
Op.onArrayFor(1,2,1,2,2).zipAndGroupValues(Types.STRING, "a","b","c","d","e").get();
</pre></div><div class="source"><pre>IFunction<Integer,String> keyEvaluatorFn = ...;
Map<String,Integer[]> map =
Op.onArrayFor(1,2,3,4,5,6).zipAndGroupKeysBy(keyEvaluatorFn).get();
</pre></div></div></div><div class="section"><h5>Coupling<a name="Coupling"></a></h5><p>The third way to create a Map from an array is by "coupling" or alternating elements, this is, by considering even elements as keys and odd elements as values (starting with 0). This will mean of course that, for a <tt>String[]</tt>, we will get a <tt>Map<String,String></tt>.</p><div class="source"><pre>// map = {{"a"="X"}, {"b"="Y"}}
Map<String,String> map =
Op.onArrayFor("a","X","b","Y").couple().get();
</pre></div><div class="section"><h6>Coupling and Grouping<a name="Coupling_and_Grouping"></a></h6><p>Again, collisions can be avoided by grouping...</p><div class="source"><pre>// map = {{"a"=["X","Y","Z"]}, {"b"=["1","2"]}}
Map<String,String[]> mapOfArray =
Op.onArrayFor("a","X","b","1","a","Y","a","Z","b","2").coupleAndGroup().get();
</pre></div></div></div></div></div><div class="section"><h3><a name="a3">3</a>. Iterating<a name="a3._Iterating"></a></h3><p>Arrays can be iterated according to the following scheme:</p><div class="source"><pre>Op.on(array).forEach().[ELEMENT ACTIONS].get();
</pre></div><p>After the <i>forEach()</i> action, any action added to the expression chain will be applied, not on the array itself, but on each of its elements, and the result obtained when executing <tt>get()</tt> will be an array with the results of applying the subsequently chained actions on each of the array elements. </p><p>Iteration can be ended with the <tt>endFor()</tt> action:</p><div class="source"><pre>Op.on(array).forEach().[ELEMENT ACTIONS].endFor().[ARRAY ACTIONS].get();
</pre></div><p>The <i>endFor()</i> action allows the subsequent execution of actions acting again on the whole array, after having executed some actions on its elements by separate between <i>forEach()</i> and <i>endFor()</i>. For example:</p><div class="source"><pre>List<String> list = Op.on(array).forEach().exec(FnString.toUpperCase()).endFor().toList().get();
</pre></div></div><div class="section"><h3><a name="a4">4</a>. Modifying<a name="a4._Modifying"></a></h3><p>An array can be modified by adding or removing elements from it. </p><p>Several options for adding new elements at the end of an array:</p><div class="source"><pre>String[] array = ...;
Collection<String> strCol = ...;
...
Op.on(array).add("new String")...
Op.on(array).addAll("new String", "another new String")...
Op.on(array).addAll(strCol)...
</pre></div><p>New elements can also be inserted into a specific position. Positions start with 0.</p><div class="source"><pre>String[] array = ...;
...
Op.on(array).insert(2, "new string")...
Op.on(array).insertAll(2, "new String", "another new String")...
</pre></div><p>Removal of elements can be done in several ways. Elements can be removed attending to their position inside the array:</p><div class="source"><pre>Op.on(array).removeAllIndexes(2,3,5)...
Op.on(array).insertAllIndexesNot(2,3,5)...
</pre></div><p>Also attending to their value:</p><div class="source"><pre>Op.on(array).removeAllEqual("Coast", "Mountain")...
</pre></div><p>Nulls can be removed easily: </p><div class="source"><pre>Op.on(array).removeAllNull()...
</pre></div><p>And finally a function returning <tt>Boolean</tt> can be used as evaluator to determine whether an element should be removed or not, in several ways:</p><div class="source"><pre>String[] array = ...;
IFunction<String,Boolean> eval = ...;
...
Op.on(array).removeAllTrue(eval)...
Op.on(array).removeAllFalse(eval)...
Op.on(array).removeAllNullOrTrue(eval)...
Op.on(array).removeAllNullOrFalse(eval)...
Op.on(array).removeAllNotNullAndTrue(eval)...
Op.on(array).removeAllNotNullAndFalse(eval)...
</pre></div></div><div class="section"><h3><a name="a5">5</a>. Executing functions<a name="a5._Executing_functions"></a></h3><div class="section"><h4>Executing functions on the array elements<a name="Executing_functions_on_the_array_elements"></a></h4><p>Due to the special condition of arrays in Java, op4j makes a difference between two ways of executing functions on them:</p><ul><li>Executions which keep the array element type (example: String[] -> String[])</li><li>Executions which change the array element type (example: String[] -> Integer[])</li></ul><div class="section"><h5>Keeping the array element type<a name="Keeping_the_array_element_type"></a></h5><p>Functions can be executed on each of the array elements after a <i>forEach()</i> action:</p><div class="source"><pre>String[] array = ...;
...
Op.on(array).forEach().exec(FnString.toUpperCase())...
</pre></div><p><tt>FnString.toUpperCase()</tt> was executable this way because it is an <tt>IFunction<String,String></tt>, and so it would not change the array element type.</p><p>A condition can be added for conditional execution, if needed:</p><div class="source"><pre>String[] array = ...;
IFunction<String,String> myFunction = ...;
...
Op.on(array).forEach().execIfNotNull(myFunction)...
</pre></div><div class="source"><pre>String[] array = ...;
IFunction<String,Boolean> condition = ...;
IFunction<String,String> myFunction = ...;
...
Op.on(array).forEach().execIfTrue(condition, myFunction)...
</pre></div><p>...an <i>else</i> side can it also be added, in which case the expression can change the type of the operator: </p><div class="source"><pre>String[] array = ...;
IFunction<String,Boolean> condition = ...;
IFunction<String,Integer> myThenFunction = ...;
IFunction<String,Integer> myElseFunction = ...;
...
Integer[] newArray =
Op.on(array).forEach().execIfTrue(condition, myThenFunction, myElseFunction).get();
</pre></div></div><div class="section"><h5>Changing the array element type<a name="Changing_the_array_element_type"></a></h5><p>When the executed function changes the array element type, the new type has to be specified in the <i>exec(...)</i> call, so that op4j is able to instantiate the new array:</p><div class="source"><pre>String[] array = ...;
...
BigDecimal[] newArray =
Op.on(array).forEach().exec(Types.BIG_DECIMAL, FnString.toBigDecimal(DecimalPoint.IS_COMMA)).get();
</pre></div></div></div><div class="section"><h4>Executing functions on the whole array<a name="Executing_functions_on_the_whole_array"></a></h4><p>If an array has not been iterated (<i>forEach()</i>) (or it has, but <i>endFor()</i> has been called), functions can be executed on the whole array. </p><p>There are three ways of executing functions on an array as a whole:</p><ul><li>Executions which return an array keeping the array element type (example: String[] -> String[])</li><li>Executions which return an array changing the array element type (example: String[] -> Integer[])</li><li>Executions which do not return an array (example: String[] -> Calendar)</li></ul><div class="section"><h5>Returning an array and keeping the array element type<a name="Returning_an_array_and_keeping_the_array_element_type"></a></h5><p>Functions will be executed using the <tt>execAsArray(...)</tt> action:</p><div class="source"><pre>String[] array = ...;
IFunction<String[],String[]> myFunction = ...;
...
Op.on(array).execAsArray(myFunction)...
</pre></div><p>A conditional check can be added (null, not null, condition true, condition false): </p><div class="source"><pre>String[] array = ...;
IFunction<String[],String[]> myFunction = ...;
...
Op.on(array).execIfNotNullAsArray(myFunction)...
</pre></div></div><div class="section"><h5>Returning an array and changing the array element type<a name="Returning_an_array_and_changing_the_array_element_type"></a></h5><div class="source"><pre>String[] array = ...;
IFunction<String[],Integer[]> myFunction = ...;
...
Op.on(array).execAsArray(Types.INTEGER, myFunction)...
</pre></div></div><div class="section"><h5>Not returning an array<a name="Not_returning_an_array"></a></h5><div class="source"><pre>String[] array = new String[] {"1978", "12", "6"};
Calendar calendar =
Op.on(array).exec(FnCalendar.fieldStringArrayToCalendar()).get();
</pre></div></div></div></div><div class="section"><h3><a name="a6">6</a>. Mapping functions<a name="a6._Mapping_functions"></a></h3><p><i>Mapping</i> an array is the equivalent to iterating it, applying a function to each of its elements and then ending the iteration:</p><div class="source"><pre>Op.on(array).map(function).get();
</pre></div><p>Is equivalent to:</p><div class="source"><pre>Op.on(array).forEach().exec(function).endFor().get();
</pre></div><p>In the same way as executing functions on array elements, there are two ways of mapping:</p><ul><li>Executions which keep the array element type (example: String[] -> String[])</li><li>Executions which change the array element type (example: String[] -> Integer[])</li></ul><div class="section"><h4>Keeping the array element type<a name="Keeping_the_array_element_type"></a></h4><p>Functions can be mapped easily:</p><div class="source"><pre>String[] array = ...;
...
Op.on(array).map(FnString.toUpperCase())...
</pre></div><p>As with <i>exec</i>, <tt>FnString.toUpperCase()</tt> was executable this way because it is an <tt>IFunction<String,String></tt>, and so it would not change the array element type.</p><p>A null condition on each of the array elements can be added for <i>null-saving</i> a function execution, if needed:</p><div class="source"><pre>String[] array = ...;
IFunction<String,String> myFunction = ...;
...
Op.on(array).mapIfNotNull(myFunction)...
</pre></div></div><div class="section"><h4>Changing the array element type<a name="Changing_the_array_element_type"></a></h4><p>When the executed function changes the array element type, the new type has to be specified in the <i>map(...)</i> call, so that op4j is able to instantiate the new array:</p><div class="source"><pre>String[] array = ...;
...
BigDecimal[] newArray =
Op.on(array).map(Types.BIG_DECIMAL, FnString.toBigDecimal(DecimalPoint.IS_COMMA)).get();
</pre></div></div></div><div class="section"><h3><a name="a7">7</a>. Selecting (conditional code)<a name="a7._Selecting_conditional_code"></a></h3><p>op4j allows the conditional execution of actions. Once the condition (an action starting with "<tt>if</tt>") is executed, all subsequent actions will apply only on the selected parts of the target object.</p><p>For example, lets convert into upper case only the first String element of the array:</p><div class="source"><pre>String[] newArray = Op.on(array).forEach().ifIndex(0).exec(FnString.toUpperCase()).get();
</pre></div><p>Selections can be ended with <tt>endIf(...)</tt>:</p><div class="source"><pre>String[] newArray =
Op.on(array).forEach().ifIndex(0,1,3).[ACTIONS ON SELECTED ELEMENTS].endIf()...
</pre></div><div class="section"><h4>Selecting specific array elements <a name="Selecting_specific_array_elements"></a></h4><p>If a selection is executed after an iteration, it will be applied on the array elements.</p><p>Selection can be done on the element's position in the array:</p><div class="source"><pre>Op.on(array).forEach().ifIndex(0,2,3)....
Op.on(array).forEach().ifIndexNot(0,1,5)....
</pre></div><p>Selection can also be based on the nullity of the element: </p><div class="source"><pre>Op.on(array).forEach().ifNull()....
Op.on(array).forEach().ifNotNull()....
</pre></div><p>And also on the value returned by the evaluation of a function returning <tt>Boolean</tt>:</p><div class="source"><pre>String[] array = ...;
IFunction<String,Boolean> eval = ...;
...
Op.on(array).forEach().ifTrue(eval)...
Op.on(array).forEach().ifFalse(eval)...
</pre></div></div><div class="section"><h4>Selecting the array as a whole <a name="Selecting_the_array_as_a_whole"></a></h4><p>Selection can also be performed on the array itself as a whole, effectively deciding whether subsequent actions will be executed at all or not. </p><div class="source"><pre>String[] array = ...;
IFunction<String[],Boolean> eval = ...;
...
Op.on(array).ifNull()....
Op.on(array).ifNotNull()....
Op.on(array).ifTrue(eval)...
Op.on(array).ifFalse(eval)...
</pre></div></div><div class="section"><h4>Restricions on execution actions after selection<a name="Restricions_on_execution_actions_after_selection"></a></h4><p>After executing a selection action, function executed by means of a <i>map</i> or an <i>exec</i> action cannot change the array type (i.e., a <tt>String[]</tt> must remain <tt>String[]</tt>.</p><p>So this would not be valid:</p><div class="source"><pre>// Will not compile!
String[] newArray =
Op.on(array).forEach().ifIndex(0,1,3).exec(FnString.toInteger()).get();
</pre></div><p>...because converting only <i>some</i> of the array elements to integer would render the array type inconsistent (some elements would be <tt>String</tt>, some other <tt>Integer</tt>).</p><p>This is perfectly valid, though:</p><div class="source"><pre>// FnString.toUpperCase is IFunction<String,String>
String[] newArray =
Op.on(array).forEach().ifIndex(0,1,3).exec(FnString.toUpperCase()).get();
</pre></div></div></div><div class="section"><h3><a name="a8">8</a> Replacing<a name="a8_Replacing"></a></h3><p>Array elements (or the array itself) can be replaced by other objects:</p><div class="source"><pre>String[] newArray =
Op.on(array).forEach().ifNull().replaceWith("[no value]").get();
</pre></div><p>...which is equivalent to:</p><div class="source"><pre>String[] newArray =
Op.on(array).forEach().replaceIfNullWith("[no value]").get();
</pre></div></div><div class="section"><h3><a name="a9">9</a>. Removing duplicates<a name="a9._Removing_duplicates"></a></h3><p>Arrays can contain duplicate elements, which can be removed by executing a <i>distinct()</i> action:</p><div class="source"><pre>String[] newArray = Op.on(array).distinct().get();
</pre></div></div><div class="section"><h3><a name="a10">10</a>. Sorting<a name="a10._Sorting"></a></h3><p>Arrays can be sorted, both using a comparator or <i>natural order</i>:</p><div class="source"><pre>String[] newArray = Op.on(array).sort().get();
</pre></div><div class="source"><pre>Comparator<String> comparator = ...;
String[] newArray = Op.on(array).sort(comparator).get();
</pre></div><p>Also, arrays can be sorted not by the elements themselves, but by the result of executing a function on the array elements:</p><div class="source"><pre>IFunction<String, Comparable<?>> function = ...;
String[] newArray = Op.on(array).sortBy(function).get();
</pre></div></div><div class="section"><h3><a name="a11">11</a>. Boolean conditions: all, any<a name="a11._Boolean_conditions:_all_any"></a></h3><p>Arrays can be applied two boolean conditions: <tt>all</tt> and <tt>any</tt>. They both need a function which will be applied to each element of the array.</p><p><tt>all(function)</tt> will return <i>TRUE</i> if the result of executing <tt>function</tt> on all the elements of the array is <i>TRUE</i>:</p><div class="source"><pre>IFunction<String, Boolean> function = ...;
Boolean allTrue = Op.on(array).all(function).get();
</pre></div><p><tt>any(function)</tt> will return <i>TRUE</i> if the result of executing <tt>function</tt> on any the elements of the array is <i>TRUE</i>:</p><div class="source"><pre>IFunction<String, Boolean> function = ...;
Boolean anyTrue = Op.on(array).any(function).get();
</pre></div></div><div class="section"><h3><a name="a12">12</a>. Reversing<a name="a12._Reversing"></a></h3><p>Arrays can be reversed, so that the order of its elements gets inverted:</p><div class="source"><pre> // array = 5,3,4,2
Integer[] array = Op.onArrayFor(2,4,3,5).reverse().get();
</pre></div></div></div>
</div>
</div>
<div class="clear">
<hr/>
</div>
<div id="footer">
<div class="xright">
Copyright © 2012
<a href="https://www.op4j.org">The OP4J team</a>.
All Rights Reserved.
</div>
<div class="clear">
<hr/>
</div>
</div>
</body>
</html>