This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
/
Enumerable.java
executable file
·587 lines (524 loc) · 18.7 KB
/
Enumerable.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
package lambda.enumerable;
import static java.lang.Boolean.*;
import static lambda.exception.UncheckedException.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import lambda.Fn0;
import lambda.Fn1;
import lambda.Fn2;
import lambda.enumerable.collection.EIterable;
import lambda.enumerable.collection.EList;
import lambda.enumerable.collection.EMap;
import lambda.enumerable.collection.ESet;
/**
* Ruby/Smalltalk style internal iterators for Java 5 using bytecode
* transformation to capture expressions as closures.
*
* <p>
* <a href="http://ruby-doc.org/core/classes/Enumerable.html"/>Ruby's Enumerable
* module</a>
* </p>
*/
public class Enumerable {
/**
* Passes each element of the collection to the given block. The method
* returns true if the block never returns false or null.
*/
public static <E> boolean all(Iterable<E> collection, Fn1<E, ?> block) {
for (E each : collection) {
Object result = block.call(each);
if (result == FALSE || result == null)
return false;
}
return true;
}
/**
* Passes each element of the collection to the given block. The method
* returns true if the block ever returns a value other than false or null.
*/
public static <E> boolean any(Iterable<E> collection, Fn1<E, ?> block) {
for (E each : collection) {
Object result = block.call(each);
if (result != FALSE && result != null)
return true;
}
return false;
}
/**
* Returns a new list with the results of running block once for every
* element in collection.
*/
public static <E, R> EList<R> collect(Iterable<E> collection, Fn1<E, R> block) {
EList<R> result = new EList<R>();
for (E each : collection)
result.add(block.call(each));
return result;
}
/**
* Passes each entry in collection to block. Returns the first for which
* block is not false. If no object matches, it returns null.
*/
public static <E> E detect(Iterable<E> collection, Fn1<E, Boolean> block) {
return detect(collection, null, block);
}
/**
* Passes each entry in collection to block. Returns the first for which
* block is not false. If no object matches, it returns ifNone.
*/
public static <E> E detect(Iterable<E> collection, E ifNone, Fn1<E, Boolean> block) {
for (E each : collection)
if (block.call(each))
return each;
return ifNone;
}
/**
* Calls block for each item in collection.
*/
public static <E, R> EIterable<E> each(Iterable<E> collection, Fn1<E, R> block) {
for (E each : collection)
block.call(each);
return EIterable.from(collection);
}
/**
* Calls block once for each key in map, passing the key and value to the
* block as parameters.
*/
public static <K, V, R> EMap<K, V> each(Map<K, V> map, Fn2<K, V, R> block) {
for (Entry<K, V> each : map.entrySet())
block.call(each.getKey(), each.getValue());
return new EMap<K, V>(map);
}
/**
* Iterates the given block for each list of consecutive n elements.
*/
public static <E, R> Object eachCons(Iterable<E> collection, int n, Fn1<List<E>, R> block) {
List<E> list = asNewList(collection);
for (int i = 0; i + n <= list.size(); i++)
if (n + i <= list.size())
block.call(list.subList(i, i + n));
return null;
}
/**
* Calls block once for each key in map, passing the key as parameter.
*/
public static <K, V, R> EMap<K, V> eachKey(Map<K, V> map, Fn1<K, R> block) {
each(map.keySet(), block);
return new EMap<K, V>(map);
}
/**
* Executes the block for every line in file.
*/
public static <R> File eachLine(File file, Fn1<String, R> block) {
try {
eachLine(new FileReader(file), block);
return file;
} catch (FileNotFoundException e) {
throw uncheck(e);
}
}
/**
* Executes the block for every line in reader.
*/
public static <R> Reader eachLine(Reader reader, Fn1<String, R> block) {
try {
BufferedReader in = new BufferedReader(reader);
String line;
while ((line = in.readLine()) != null)
block.call(line);
return reader;
} catch (IOException e) {
throw uncheck(e);
} finally {
try {
reader.close();
} catch (IOException silent) {
}
}
}
/**
* Executes the block for every line in string.
*/
public static <R> String eachLine(String string, Fn1<String, R> block) {
eachLine(new StringReader(string), block);
return string;
}
/**
* Iterates the given block for each slice of n elements.
*/
public static <E, R> Object eachSlice(Iterable<E> collection, int n, Fn1<List<E>, R> block) {
List<E> list = asNewList(collection);
for (int i = 0; i <= list.size(); i += n)
if (i + n > list.size())
block.call(list.subList(i, list.size()));
else
block.call(list.subList(i, i + n));
return null;
}
/**
* Calls block once for each value in map, passing the key as parameter.
*/
public static <K, V, R> EMap<K, V> eachValue(Map<K, V> map, Fn1<V, R> block) {
each(map.values(), block);
return new EMap<K, V>(map);
}
/**
* Calls block with two arguments, the item and its index, for each item in
* collection.
*/
public static <E, R> EIterable<E> eachWithIndex(Iterable<E> collection, Fn2<E, Integer, R> block) {
int i = 0;
for (E each : collection)
block.call(each, i++);
return EIterable.from(collection);
}
/**
* @see #toList(Iterable)
*/
public static <E> EList<E> entries(Iterable<E> collection) {
return toList(collection);
}
/**
* @see #detect(Iterable, Fn1)
*/
public static <E> E find(Iterable<E> collection, Fn1<E, Boolean> block) {
return detect(collection, block);
}
/**
* @see #detect(Iterable, Object, Fn1)
*/
public static <E> E find(Iterable<E> collection, E ifNone, Fn1<E, Boolean> block) {
return detect(collection, ifNone, block);
}
/**
* @see #select(Iterable, Fn1)
*/
public static <E> EList<E> findAll(Iterable<E> collection, Fn1<E, Boolean> block) {
return select(collection, block);
}
/**
* Returns a list of every element in collection for which pattern matches.
*/
public static <E> EList<E> grep(Iterable<E> collection, Pattern pattern) {
EList<E> result = new EList<E>();
for (E each : collection)
if (pattern.matcher(each.toString()).matches())
result.add(each);
return result;
}
/**
* Returns a list of every element in collection for which pattern matches.
* Each matching element is passed to tje block, and its result is stored in
* the output list.
*/
public static <E, R> EList<R> grep(Iterable<E> collection, Pattern pattern, Fn1<E, R> block) {
EList<R> result = new EList<R>();
for (E each : collection)
if (pattern.matcher(each.toString()).matches())
result.add(block.call(each));
return result;
}
/**
* @see #grep(Iterable, Pattern)
*/
public static <E> EList<E> grep(Iterable<E> collection, String pattern) {
return grep(collection, Pattern.compile(pattern));
}
/**
* @see #grep(Iterable, Pattern, Fn1)
*/
public static <E, R> EList<R> grep(Iterable<E> collection, String pattern, Fn1<E, R> block) {
return grep(collection, Pattern.compile(pattern), block);
}
/**
* Named parameter for detect.
*
* @see #detect(Iterable, Object, Fn1)
* @see #find(Iterable, Object, Fn1)
*/
public static <R> R ifNone(R defaultValue) {
return defaultValue;
}
/**
* @see #member(Iterable, Object)
*/
public static <E> boolean includes(Iterable<E> collection, Object obj) {
return asNewList(collection).contains(obj);
}
/**
* Combines the elements of collection by applying the block to an
* accumulator value (memo) and each element in turn. At each step, memo is
* set to the value returned by the block. This form uses the first element
* of the collection as a the initial value (and skips that element while
* iterating).
*/
public static <E> E inject(Iterable<E> collection, Fn2<E, E, E> block) {
Iterator<E> i = collection.iterator();
if (!i.hasNext())
return null;
E initial = i.next();
while (i.hasNext())
initial = block.call(initial, i.next());
return initial;
}
/**
* Combines the elements of collection by applying the block to an
* accumulator value (memo) and each element in turn. At each step, memo is
* set to the value returned by the block. This form lets you supply an
* initial value for memo.
*/
public static <E, R> R inject(Iterable<E> collection, R initial, Fn2<R, E, R> block) {
for (E each : collection)
initial = block.call(initial, each);
return initial;
}
/**
* @see #collect(Iterable, Fn1)
*/
public static <E, R> EList<R> map(Iterable<E> collection, Fn1<E, R> block) {
return collect(collection, block);
}
/**
* Returns the object in collection with the maximum value. This form
* assumes all objects implement {@link Comparable}
*/
public static <E extends Object & Comparable<? super E>> E max(Iterable<E> collection) {
return min(collection, new ReverseComparator<E>(new NaturalOrderComparator<E>()));
}
/**
* Returns the object in collection with the maximum value. This form uses
* the block to {@link Comparator#compare}.
*/
@SuppressWarnings("unchecked")
public static <E> E max(Iterable<E> collection, Fn2<E, E, Integer> block) {
return min(collection, new ReverseComparator<E>(block.as(Comparator.class)));
}
/**
* Returns true if any member of collection equals obj. Equality is tested
* using {@link Object#equals(Object)}.
*/
public static <E> boolean member(Iterable<E> collection, Object obj) {
return includes(collection, obj);
}
/**
* Returns the object in collection with the minimum value. This form
* assumes all objects implement {@link Comparable}.
*/
public static <E extends Object & Comparable<? super E>> E min(Iterable<E> collection) {
return min(collection, new NaturalOrderComparator<E>());
}
/**
* Returns the object in collection with the minimum value. This form uses
* the block to {@link Comparator#compare}.
*/
@SuppressWarnings("unchecked")
public static <E> E min(Iterable<E> collection, Fn2<E, E, Integer> block) {
return min(collection, (Comparator<E>) block.as(Comparator.class));
}
/**
* Returns two lists, the first containing the elements of collection for
* which the block evaluates to true, the second containing the rest.
*/
public static <E> EList<EList<E>> partition(Iterable<E> collection, Fn1<E, Boolean> block) {
EList<E> selected = new EList<E>();
EList<E> rejected = new EList<E>();
for (E each : collection)
if (block.call(each))
selected.add(each);
else
rejected.add(each);
EList<EList<E>> result = new EList<EList<E>>();
result.add(selected);
result.add(rejected);
return result;
}
/**
* Constructs a range using the given start and end. The range will include
* the end object.
*/
public static Range range(int start, int end) {
return range(start, end, false);
}
/**
* Constructs a range using the given start and end. If the third parameter
* is false, the range will include the end object; otherwise, it will be
* excluded.
*/
public static Range range(int start, int end, boolean exclusive) {
return new Range(start, end, exclusive);
}
/**
* @see #times(int, Fn1)
*/
public static int times(int i, Fn0<?> block) {
Iterator<Integer> range = range(0, i, true).iterator();
for (; range.hasNext(); range.next())
block.call();
return i;
}
/**
* Iterates block i times, passing in values from zero to i - 1.
*/
public static int times(int i, Fn1<Integer, ?> block) {
each(range(0, i, true), block);
return i;
}
/**
* Returns a list containing all elements of collection for which block is
* false.
*/
public static <E> EList<E> reject(Iterable<E> collection, Fn1<E, Boolean> block) {
EList<E> result = new EList<E>();
for (E each : collection)
if (!block.call(each))
result.add(each);
return result;
}
/**
* Returns a list containing all elements of collection for which block is
* not false.
*/
public static <E> EList<E> select(Iterable<E> collection, Fn1<E, Boolean> block) {
EList<E> result = new EList<E>();
for (E each : collection)
if (block.call(each))
result.add(each);
return result;
}
/**
* Returns a list containing all Map.Entry pairs for which the block returns
* true.
*/
public static <K, V> EList<Map.Entry<K, V>> select(Map<K, V> map, Fn2<K, V, Boolean> block) {
EList<Map.Entry<K, V>> result = new EList<Map.Entry<K, V>>();
for (Map.Entry<K, V> each : map.entrySet())
if (block.call(each.getKey(), each.getValue()))
result.add(each);
return result;
}
/**
* Returns a list containing the items in collection sorted, according to
* their own compareTo method.
*/
public static <E extends Object & Comparable<? super E>> EList<E> sort(Iterable<E> collection) {
return sort(collection, (Comparator<E>) null);
}
private static <E> EList<E> sort(Iterable<E> collection, Comparator<E> comparator) {
List<E> result = asNewList(collection);
Collections.sort(result, comparator);
return new EList<E>(result);
}
/**
* Returns a list containing the items in collection sorted by using the
* results of the supplied block.
*/
@SuppressWarnings("unchecked")
public static <E> EList<E> sort(Iterable<E> collection, Fn2<E, E, Integer> block) {
return sort(collection, block.as(Comparator.class));
}
/**
* Sorts collection using a set of keys generated by mapping the values in
* collection through the given block.
*/
public static <E, R extends Object & Comparable<? super R>> EList<E> sortBy(Iterable<E> collection,
final Fn1<E, R> block) {
return sort(collection, new Comparator<E>() {
public int compare(E o1, E o2) {
return block.call(o1).compareTo(block.call(o2));
}
});
}
/**
* Returns a list containing the items in collection.
*/
public static <E> EList<E> toList(Iterable<E> collection) {
return new EList<E>(asNewList(collection));
}
/**
* Creates a new Set containing the elements of the given collection.
*/
public static <E> ESet<E> toSet(Iterable<E> collection) {
return new ESet<E>(new HashSet<E>(asNewList(collection)));
}
/**
* Creates a new Set containing the elements of the given collection, the
* elements are preprocessed by the given block.
*/
public static <E, R> ESet<R> toSet(Iterable<E> collection, Fn1<E, R> block) {
return toSet(collect(collection, block));
}
/**
* Converts any arguments to iterators, then merges elements of collection
* with corresponding elements from each argument. This generates a sequence
* of collection#size n-element list, where n is one more that the count of
* arguments. If the size of any argument is less than collection#size, null
* values are supplied.
*
* <p>
* Due to varargs this version doesn't support taking a block like in Ruby.
* Feed the result into {@link #collect(Iterable, Fn1)} to achieve the same
* effect.
* </p>
*/
public static <E> EList<EList<?>> zip(Iterable<E> collection, Iterable<?>... args) {
EList<EList<?>> allResults = new EList<EList<?>>();
List<Iterator<?>> iterators = new ArrayList<Iterator<?>>();
iterators.add(collection.iterator());
for (Iterable<?> iterable : args)
iterators.add(iterable.iterator());
while (iterators.get(0).hasNext()) {
EList<Object> result = new EList<Object>();
for (Iterator<?> iterator : iterators)
if (iterator.hasNext())
result.add(iterator.next());
else
result.add(null);
allResults.add(result);
}
return allResults;
}
private static <E> List<E> asNewList(Iterable<E> collection) {
if (collection instanceof Collection<?>)
return new ArrayList<E>((Collection<E>) collection);
List<E> result = new ArrayList<E>();
for (E each : collection)
result.add(each);
return result;
}
private static <E> E min(Iterable<E> collection, Comparator<E> comparator) {
E result = null;
for (E each : collection)
if (result == null || comparator.compare(each, result) < 0)
result = each;
return result;
}
private static final class ReverseComparator<E> implements Comparator<E> {
Comparator<E> comparator;
ReverseComparator(Comparator<E> comparator) {
this.comparator = comparator;
}
public int compare(E o1, E o2) {
return -comparator.compare(o1, o2);
}
}
private static final class NaturalOrderComparator<E extends Object & Comparable<? super E>> implements
Comparator<E> {
public int compare(E o1, E o2) {
return o1.compareTo(o2);
}
}
}