• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

javadev / underscore-java / #3671

25 Dec 2023 04:05AM CUT coverage: 100.0%. Remained the same
#3671

push

web-flow
Updated underscore.js

4347 of 4347 relevant lines covered (100.0%)

1.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/src/main/java/com/github/underscore/Underscore.java
1
/*
2
 * The MIT License (MIT)
3
 *
4
 * Copyright 2015-2023 Valentyn Kolesnikov
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
package com.github.underscore;
25

26
import java.lang.reflect.Field;
27
import java.lang.reflect.Method;
28
import java.util.ArrayDeque;
29
import java.util.ArrayList;
30
import java.util.Arrays;
31
import java.util.Collection;
32
import java.util.Collections;
33
import java.util.Comparator;
34
import java.util.Date;
35
import java.util.Deque;
36
import java.util.HashMap;
37
import java.util.Iterator;
38
import java.util.LinkedHashMap;
39
import java.util.LinkedHashSet;
40
import java.util.List;
41
import java.util.ListIterator;
42
import java.util.Map;
43
import java.util.Objects;
44
import java.util.Optional;
45
import java.util.Set;
46
import java.util.UUID;
47
import java.util.function.BiConsumer;
48
import java.util.function.BiFunction;
49
import java.util.function.BinaryOperator;
50
import java.util.function.Consumer;
51
import java.util.function.Function;
52
import java.util.function.Predicate;
53
import java.util.function.Supplier;
54
import java.util.function.UnaryOperator;
55

56
/**
57
 * Underscore-java is a java port of Underscore.js.
58
 *
59
 * @author Valentyn Kolesnikov
60
 */
61
@SuppressWarnings({
62
    "java:S106",
63
    "java:S2189",
64
    "java:S2272",
65
    "java:S2789",
66
    "java:S3740",
67
    "java:S5852"
68
})
69
public class Underscore<T> {
70
    private static final Map<String, Function<String, String>> FUNCTIONS = new LinkedHashMap<>();
1✔
71
    private static final Map<String, String> TEMPLATE_SETTINGS = new HashMap<>();
1✔
72
    private static final int MIN_PASSWORD_LENGTH_8 = 8;
73
    private static final long CAPACITY_SIZE_5 = 5L;
74
    private static final long CAPACITY_COEFF_2 = 2L;
75
    private static final long CAPACITY_SIZE_16 = 16L;
76
    private static final java.util.concurrent.atomic.AtomicInteger UNIQUE_ID =
1✔
77
            new java.util.concurrent.atomic.AtomicInteger(0);
78
    private static final String ALL_SYMBOLS = "([\\s\\S]+?)";
79
    private static final String EVALUATE = "evaluate";
80
    private static final String INTERPOLATE = "interpolate";
81
    private static final String ESCAPE = "escape";
82
    private static final String S_Q = "\\s*\\Q";
83
    private static final String E_S = "\\E\\s*";
84
    private static final java.util.regex.Pattern FORMAT_PATTERN =
1✔
85
            java.util.regex.Pattern.compile("\\{\\s*(\\d*)\\s*\\}");
1✔
86
    private static final Map<Character, String> ESCAPES = new HashMap<>();
1✔
87
    private final Iterable<T> iterable;
88
    private final Optional<String> string;
89

90
    static {
91
        TEMPLATE_SETTINGS.put(EVALUATE, "<%([\\s\\S]+?)%>");
1✔
92
        TEMPLATE_SETTINGS.put(INTERPOLATE, "<%=([\\s\\S]+?)%>");
1✔
93
        TEMPLATE_SETTINGS.put(ESCAPE, "<%-([\\s\\S]+?)%>");
1✔
94
        ESCAPES.put('&', "&amp;");
1✔
95
        ESCAPES.put('<', "&lt;");
1✔
96
        ESCAPES.put('>', "&gt;");
1✔
97
        ESCAPES.put('"', "&quot;");
1✔
98
        ESCAPES.put('\'', "&#x27;");
1✔
99
        ESCAPES.put('`', "&#x60;");
1✔
100
    }
1✔
101

102
    public Underscore(final Iterable<T> iterable) {
1✔
103
        this.iterable = iterable;
1✔
104
        this.string = Optional.empty();
1✔
105
    }
1✔
106

107
    public Underscore(final String string) {
1✔
108
        this.iterable = null;
1✔
109
        this.string = Optional.of(string);
1✔
110
    }
1✔
111

112
    private static void setTemplateKey(
113
            final Map<String, String> templateSettings, final String key) {
114
        if (templateSettings.containsKey(key) && templateSettings.get(key).contains(ALL_SYMBOLS)) {
1✔
115
            TEMPLATE_SETTINGS.put(key, templateSettings.get(key));
1✔
116
        }
117
    }
1✔
118

119
    public static void templateSettings(final Map<String, String> templateSettings) {
120
        setTemplateKey(templateSettings, EVALUATE);
1✔
121
        setTemplateKey(templateSettings, INTERPOLATE);
1✔
122
        setTemplateKey(templateSettings, ESCAPE);
1✔
123
    }
1✔
124

125
    private static final class WherePredicate<E, T> implements Predicate<E> {
126
        private final List<Map.Entry<String, T>> properties;
127

128
        private WherePredicate(List<Map.Entry<String, T>> properties) {
1✔
129
            this.properties = properties;
1✔
130
        }
1✔
131

132
        @Override
133
        public boolean test(final E elem) {
134
            for (Map.Entry<String, T> prop : properties) {
1✔
135
                try {
136
                    if (!elem.getClass()
1✔
137
                            .getField(prop.getKey())
1✔
138
                            .get(elem)
1✔
139
                            .equals(prop.getValue())) {
1✔
140
                        return false;
1✔
141
                    }
142
                } catch (Exception ex) {
1✔
143
                    try {
144
                        if (!elem.getClass()
1✔
145
                                .getMethod(prop.getKey())
1✔
146
                                .invoke(elem)
1✔
147
                                .equals(prop.getValue())) {
1✔
148
                            return false;
1✔
149
                        }
150
                    } catch (Exception ignored) {
1✔
151
                        // ignored
152
                    }
1✔
153
                }
1✔
154
            }
1✔
155
            return true;
1✔
156
        }
157
    }
158

159
    private static final class TemplateImpl<K, V> implements Template<Map<K, V>> {
160
        private final String template;
161

162
        private TemplateImpl(String template) {
1✔
163
            this.template = template;
1✔
164
        }
1✔
165

166
        @Override
167
        public String apply(Map<K, V> value) {
168
            final String evaluate = TEMPLATE_SETTINGS.get(EVALUATE);
1✔
169
            final String interpolate = TEMPLATE_SETTINGS.get(INTERPOLATE);
1✔
170
            final String escape = TEMPLATE_SETTINGS.get(ESCAPE);
1✔
171
            String result = template;
1✔
172
            for (final Map.Entry<K, V> element : value.entrySet()) {
1✔
173
                final String value1 =
1✔
174
                        String.valueOf(element.getValue())
1✔
175
                                .replace("\\", "\\\\")
1✔
176
                                .replace("$", "\\$");
1✔
177
                result =
1✔
178
                        java.util.regex.Pattern.compile(
1✔
179
                                        interpolate.replace(
1✔
180
                                                ALL_SYMBOLS, S_Q + element.getKey() + E_S))
1✔
181
                                .matcher(result)
1✔
182
                                .replaceAll(value1);
1✔
183
                result =
1✔
184
                        java.util.regex.Pattern.compile(
1✔
185
                                        escape.replace(ALL_SYMBOLS, S_Q + element.getKey() + E_S))
1✔
186
                                .matcher(result)
1✔
187
                                .replaceAll(escape(value1));
1✔
188
                result =
1✔
189
                        java.util.regex.Pattern.compile(
1✔
190
                                        evaluate.replace(ALL_SYMBOLS, S_Q + element.getKey() + E_S))
1✔
191
                                .matcher(result)
1✔
192
                                .replaceAll(value1);
1✔
193
            }
1✔
194
            return result;
1✔
195
        }
196

197
        @Override
198
        public List<String> check(Map<K, V> value) {
199
            final String evaluate = TEMPLATE_SETTINGS.get(EVALUATE);
1✔
200
            final String interpolate = TEMPLATE_SETTINGS.get(INTERPOLATE);
1✔
201
            final String escape = TEMPLATE_SETTINGS.get(ESCAPE);
1✔
202
            String result = template;
1✔
203
            final List<String> notFound = new ArrayList<>();
1✔
204
            final List<String> valueKeys = new ArrayList<>();
1✔
205
            for (final Map.Entry<K, V> element : value.entrySet()) {
1✔
206
                final String key = "" + element.getKey();
1✔
207
                java.util.regex.Matcher matcher =
1✔
208
                        java.util.regex.Pattern.compile(
1✔
209
                                        interpolate.replace(ALL_SYMBOLS, S_Q + key + E_S))
1✔
210
                                .matcher(result);
1✔
211
                boolean isFound = matcher.find();
1✔
212
                result = matcher.replaceAll(String.valueOf(element.getValue()));
1✔
213
                matcher =
1✔
214
                        java.util.regex.Pattern.compile(
1✔
215
                                        escape.replace(ALL_SYMBOLS, S_Q + key + E_S))
1✔
216
                                .matcher(result);
1✔
217
                isFound |= matcher.find();
1✔
218
                result = matcher.replaceAll(escape(String.valueOf(element.getValue())));
1✔
219
                matcher =
1✔
220
                        java.util.regex.Pattern.compile(
1✔
221
                                        evaluate.replace(ALL_SYMBOLS, S_Q + key + E_S))
1✔
222
                                .matcher(result);
1✔
223
                isFound |= matcher.find();
1✔
224
                result = matcher.replaceAll(String.valueOf(element.getValue()));
1✔
225
                if (!isFound) {
1✔
226
                    notFound.add(key);
1✔
227
                }
228
                valueKeys.add(key);
1✔
229
            }
1✔
230
            final List<String> templateVars = new ArrayList<>();
1✔
231
            java.util.regex.Matcher matcher =
1✔
232
                    java.util.regex.Pattern.compile(interpolate).matcher(result);
1✔
233
            while (matcher.find()) {
1✔
234
                templateVars.add(matcher.group(1).trim());
1✔
235
            }
236
            result = matcher.replaceAll("");
1✔
237
            matcher = java.util.regex.Pattern.compile(escape).matcher(result);
1✔
238
            while (matcher.find()) {
1✔
239
                templateVars.add(matcher.group(1).trim());
1✔
240
            }
241
            result = matcher.replaceAll("");
1✔
242
            matcher = java.util.regex.Pattern.compile(evaluate).matcher(result);
1✔
243
            while (matcher.find()) {
1✔
244
                templateVars.add(matcher.group(1).trim());
1✔
245
            }
246
            notFound.addAll(difference(templateVars, valueKeys));
1✔
247
            return notFound;
1✔
248
        }
249
    }
250

251
    private static final class MyIterable<T> implements Iterable<T> {
252
        private final UnaryOperator<T> unaryOperator;
253
        private boolean firstRun = true;
1✔
254
        private T value;
255

256
        MyIterable(final T seed, final UnaryOperator<T> unaryOperator) {
1✔
257
            this.value = seed;
1✔
258
            this.unaryOperator = unaryOperator;
1✔
259
        }
1✔
260

261
        public Iterator<T> iterator() {
262
            return new Iterator<>() {
1✔
263
                @Override
264
                public boolean hasNext() {
265
                    return true;
1✔
266
                }
267

268
                @Override
269
                public T next() {
270
                    if (firstRun) {
1✔
271
                        firstRun = false;
1✔
272
                    } else {
273
                        value = unaryOperator.apply(value);
1✔
274
                    }
275
                    return value;
1✔
276
                }
277

278
                @Override
279
                public void remove() {
280
                    // ignored
281
                }
1✔
282
            };
283
        }
284
    }
285

286
    public static <K, V> Function<Map<K, V>, V> iteratee(final K key) {
287
        return item -> item.get(key);
1✔
288
    }
289

290
    /*
291
     * Documented, #each
292
     */
293
    public static <T> void each(final Iterable<T> iterable, final Consumer<? super T> func) {
294
        for (T element : iterable) {
1✔
295
            func.accept(element);
1✔
296
        }
1✔
297
    }
1✔
298

299
    public static <T> void eachIndexed(
300
            final Iterable<T> iterable, final BiConsumer<Integer, ? super T> func) {
301
        int index = 0;
1✔
302
        for (T element : iterable) {
1✔
303
            func.accept(index, element);
1✔
304
            index += 1;
1✔
305
        }
1✔
306
    }
1✔
307

308
    public void each(final Consumer<? super T> func) {
309
        each(iterable, func);
1✔
310
    }
1✔
311

312
    public static <T> void eachRight(final Iterable<T> iterable, final Consumer<? super T> func) {
313
        each(reverse(iterable), func);
1✔
314
    }
1✔
315

316
    public void eachRight(final Consumer<? super T> func) {
317
        eachRight(iterable, func);
1✔
318
    }
1✔
319

320
    public static <T> void forEach(final Iterable<T> iterable, final Consumer<? super T> func) {
321
        each(iterable, func);
1✔
322
    }
1✔
323

324
    public static <T> void forEachIndexed(
325
            final Iterable<T> iterable, final BiConsumer<Integer, ? super T> func) {
326
        eachIndexed(iterable, func);
1✔
327
    }
1✔
328

329
    public void forEach(final Consumer<? super T> func) {
330
        each(iterable, func);
1✔
331
    }
1✔
332

333
    public void forEachIndexed(final BiConsumer<Integer, ? super T> func) {
334
        eachIndexed(iterable, func);
1✔
335
    }
1✔
336

337
    public static <T> void forEachRight(
338
            final Iterable<T> iterable, final Consumer<? super T> func) {
339
        eachRight(iterable, func);
1✔
340
    }
1✔
341

342
    public void forEachRight(final Consumer<? super T> func) {
343
        eachRight(iterable, func);
1✔
344
    }
1✔
345

346
    /*
347
     * Documented, #map
348
     */
349
    public static <T, E> List<T> map(final List<E> list, final Function<? super E, T> func) {
350
        final List<T> transformed = newArrayListWithExpectedSize(list.size());
1✔
351
        for (E element : list) {
1✔
352
            transformed.add(func.apply(element));
1✔
353
        }
1✔
354
        return transformed;
1✔
355
    }
356

357
    public static <T, E> List<T> mapMulti(
358
            final List<E> list, final BiConsumer<? super E, ? super Consumer<T>> mapper) {
359
        final List<T> transformed = newArrayListWithExpectedSize(list.size());
1✔
360
        for (E element : list) {
1✔
361
            Consumer<T> value = transformed::add;
1✔
362
            mapper.accept(element, value);
1✔
363
        }
1✔
364
        return transformed;
1✔
365
    }
366

367
    public <F> List<F> map(final Function<? super T, F> func) {
368
        return map(newArrayList(iterable), func);
1✔
369
    }
370

371
    public static <T> List<T> map(final int[] array, final Function<? super Integer, T> func) {
372
        final List<T> transformed = newArrayListWithExpectedSize(array.length);
1✔
373
        for (int element : array) {
1✔
374
            transformed.add(func.apply(element));
1✔
375
        }
376
        return transformed;
1✔
377
    }
378

379
    public static <T, E> Set<T> map(final Set<E> set, final Function<? super E, T> func) {
380
        final Set<T> transformed = newLinkedHashSetWithExpectedSize(set.size());
1✔
381
        for (E element : set) {
1✔
382
            transformed.add(func.apply(element));
1✔
383
        }
1✔
384
        return transformed;
1✔
385
    }
386

387
    public static <T, E> List<T> mapIndexed(
388
            final List<E> list, final BiFunction<Integer, ? super E, T> func) {
389
        final List<T> transformed = newArrayListWithExpectedSize(list.size());
1✔
390
        int index = 0;
1✔
391
        for (E element : list) {
1✔
392
            transformed.add(func.apply(index, element));
1✔
393
            index += 1;
1✔
394
        }
1✔
395
        return transformed;
1✔
396
    }
397

398
    public static <T> List<T> replace(
399
            final Iterable<T> iter, final Predicate<T> pred, final T value) {
400
        List<T> list = newArrayList(iter);
1✔
401
        if (pred == null) {
1✔
402
            return list;
1✔
403
        }
404
        ListIterator<T> itera = list.listIterator();
1✔
405
        while (itera.hasNext()) {
1✔
406
            if (pred.test(itera.next())) {
1✔
407
                itera.set(value);
1✔
408
            }
409
        }
410
        return list;
1✔
411
    }
412

413
    public List<T> replace(final Predicate<T> pred, final T value) {
414
        return replace(value(), pred, value);
1✔
415
    }
416

417
    public static <T> List<T> replaceIndexed(
418
            final Iterable<T> iter, final PredicateIndexed<T> pred, final T value) {
419
        List<T> list = newArrayList(iter);
1✔
420
        if (pred == null) {
1✔
421
            return list;
1✔
422
        }
423
        ListIterator<T> itera = list.listIterator();
1✔
424
        int index = 0;
1✔
425
        while (itera.hasNext()) {
1✔
426
            if (pred.test(index, itera.next())) {
1✔
427
                itera.set(value);
1✔
428
            }
429
            index++;
1✔
430
        }
431
        return list;
1✔
432
    }
433

434
    public List<T> replaceIndexed(final PredicateIndexed<T> pred, final T value) {
435
        return replaceIndexed(value(), pred, value);
1✔
436
    }
437

438
    public <F> List<F> mapIndexed(final BiFunction<Integer, ? super T, F> func) {
439
        return mapIndexed(newArrayList(iterable), func);
1✔
440
    }
441

442
    public static <T, E> List<T> collect(final List<E> list, final Function<? super E, T> func) {
443
        return map(list, func);
1✔
444
    }
445

446
    public static <T, E> Set<T> collect(final Set<E> set, final Function<? super E, T> func) {
447
        return map(set, func);
1✔
448
    }
449

450
    /*
451
     * Documented, #reduce
452
     */
453
    public static <T, E> E reduce(
454
            final Iterable<T> iterable, final BiFunction<E, T, E> func, final E zeroElem) {
455
        E accum = zeroElem;
1✔
456
        for (T element : iterable) {
1✔
457
            accum = func.apply(accum, element);
1✔
458
        }
1✔
459
        return accum;
1✔
460
    }
461

462
    public static <T> Optional<T> reduce(final Iterable<T> iterable, final BinaryOperator<T> func) {
463
        boolean foundAny = false;
1✔
464
        T accum = null;
1✔
465
        for (T element : iterable) {
1✔
466
            if (foundAny) {
1✔
467
                accum = func.apply(accum, element);
1✔
468
            } else {
469
                foundAny = true;
1✔
470
                accum = element;
1✔
471
            }
472
        }
1✔
473
        return foundAny ? Optional.of(accum) : Optional.empty();
1✔
474
    }
475

476
    public static <E> E reduce(
477
            final int[] array, final BiFunction<E, ? super Integer, E> func, final E zeroElem) {
478
        E accum = zeroElem;
1✔
479
        for (int element : array) {
1✔
480
            accum = func.apply(accum, element);
1✔
481
        }
482
        return accum;
1✔
483
    }
484

485
    public static <T, E> E reduce(
486
            final T[] array, final BiFunction<E, T, E> func, final E zeroElem) {
487
        E accum = zeroElem;
1✔
488
        for (T element : array) {
1✔
489
            accum = func.apply(accum, element);
1✔
490
        }
491
        return accum;
1✔
492
    }
493

494
    public static <T, E> E foldl(
495
            final Iterable<T> iterable, final BiFunction<E, T, E> func, final E zeroElem) {
496
        return reduce(iterable, func, zeroElem);
1✔
497
    }
498

499
    public static <T, E> E inject(
500
            final Iterable<T> iterable, final BiFunction<E, T, E> func, final E zeroElem) {
501
        return reduce(iterable, func, zeroElem);
1✔
502
    }
503

504
    /*
505
     * Documented, #reduceRight
506
     */
507
    public static <T, E> E reduceRight(
508
            final Iterable<T> iterable, final BiFunction<E, T, E> func, final E zeroElem) {
509
        return reduce(reverse(iterable), func, zeroElem);
1✔
510
    }
511

512
    public static <T> Optional<T> reduceRight(
513
            final Iterable<T> iterable, final BinaryOperator<T> func) {
514
        return reduce(reverse(iterable), func);
1✔
515
    }
516

517
    public static <E> E reduceRight(
518
            final int[] array, final BiFunction<E, ? super Integer, E> func, final E zeroElem) {
519
        E accum = zeroElem;
1✔
520
        for (Integer element : reverse(array)) {
1✔
521
            accum = func.apply(accum, element);
1✔
522
        }
1✔
523
        return accum;
1✔
524
    }
525

526
    public static <T, E> E reduceRight(
527
            final T[] array, final BiFunction<E, T, E> func, final E zeroElem) {
528
        return reduce(reverse(array), func, zeroElem);
1✔
529
    }
530

531
    public static <T, E> E foldr(
532
            final Iterable<T> iterable, final BiFunction<E, T, E> func, final E zeroElem) {
533
        return reduceRight(iterable, func, zeroElem);
1✔
534
    }
535

536
    /*
537
     * Documented, #find
538
     */
539
    public static <E> Optional<E> find(final Iterable<E> iterable, final Predicate<E> pred) {
540
        for (E element : iterable) {
1✔
541
            if (pred.test(element)) {
1✔
542
                return isNull(element) ? null : Optional.of(element);
1✔
543
            }
544
        }
1✔
545
        return Optional.empty();
1✔
546
    }
547

548
    public static <E> Optional<E> detect(final Iterable<E> iterable, final Predicate<E> pred) {
549
        return find(iterable, pred);
1✔
550
    }
551

552
    public static <E> Optional<E> findLast(final Iterable<E> iterable, final Predicate<E> pred) {
553
        return find(reverse(iterable), pred);
1✔
554
    }
555

556
    /*
557
     * Documented, #filter
558
     */
559
    public static <E> List<E> filter(final Iterable<E> iterable, final Predicate<E> pred) {
560
        final List<E> filtered = new ArrayList<>();
1✔
561
        for (E element : iterable) {
1✔
562
            if (pred.test(element)) {
1✔
563
                filtered.add(element);
1✔
564
            }
565
        }
1✔
566
        return filtered;
1✔
567
    }
568

569
    public static <E> List<E> filter(final List<E> list, final Predicate<E> pred) {
570
        final List<E> filtered = new ArrayList<>();
1✔
571
        for (E element : list) {
1✔
572
            if (pred.test(element)) {
1✔
573
                filtered.add(element);
1✔
574
            }
575
        }
1✔
576
        return filtered;
1✔
577
    }
578

579
    public List<T> filter(final Predicate<T> pred) {
580
        final List<T> filtered = new ArrayList<>();
1✔
581
        for (final T element : value()) {
1✔
582
            if (pred.test(element)) {
1✔
583
                filtered.add(element);
1✔
584
            }
585
        }
1✔
586
        return filtered;
1✔
587
    }
588

589
    public static <E> List<E> filterIndexed(final List<E> list, final PredicateIndexed<E> pred) {
590
        final List<E> filtered = new ArrayList<>();
1✔
591
        int index = 0;
1✔
592
        for (E element : list) {
1✔
593
            if (pred.test(index, element)) {
1✔
594
                filtered.add(element);
1✔
595
            }
596
            index += 1;
1✔
597
        }
1✔
598
        return filtered;
1✔
599
    }
600

601
    public static <E> Set<E> filter(final Set<E> set, final Predicate<E> pred) {
602
        final Set<E> filtered = new LinkedHashSet<>();
1✔
603
        for (E element : set) {
1✔
604
            if (pred.test(element)) {
1✔
605
                filtered.add(element);
1✔
606
            }
607
        }
1✔
608
        return filtered;
1✔
609
    }
610

611
    public static <E> List<E> select(final List<E> list, final Predicate<E> pred) {
612
        return filter(list, pred);
1✔
613
    }
614

615
    public static <E> Set<E> select(final Set<E> set, final Predicate<E> pred) {
616
        return filter(set, pred);
1✔
617
    }
618

619
    /*
620
     * Documented, #reject
621
     */
622
    public static <E> List<E> reject(final List<E> list, final Predicate<E> pred) {
623
        return filter(list, input -> !pred.test(input));
1✔
624
    }
625

626
    public List<T> reject(final Predicate<T> pred) {
627
        return filter(input -> !pred.test(input));
1✔
628
    }
629

630
    public static <E> List<E> rejectIndexed(final List<E> list, final PredicateIndexed<E> pred) {
631
        return filterIndexed(list, (index, input) -> !pred.test(index, input));
1✔
632
    }
633

634
    public static <E> Set<E> reject(final Set<E> set, final Predicate<E> pred) {
635
        return filter(set, input -> !pred.test(input));
1✔
636
    }
637

638
    public static <E> List<E> filterFalse(final List<E> list, final Predicate<E> pred) {
639
        return reject(list, pred);
1✔
640
    }
641

642
    public List<T> filterFalse(final Predicate<T> pred) {
643
        return reject(pred);
1✔
644
    }
645

646
    public static <E> Set<E> filterFalse(final Set<E> set, final Predicate<E> pred) {
647
        return reject(set, pred);
1✔
648
    }
649

650
    public static <E> boolean every(final Iterable<E> iterable, final Predicate<E> pred) {
651
        for (E item : iterable) {
1✔
652
            if (!pred.test(item)) {
1✔
653
                return false;
1✔
654
            }
655
        }
1✔
656
        return true;
1✔
657
    }
658

659
    public boolean every(final Predicate<T> pred) {
660
        return every(iterable, pred);
1✔
661
    }
662

663
    /*
664
     * Documented, #all
665
     */
666
    public static <E> boolean all(final Iterable<E> iterable, final Predicate<E> pred) {
667
        return every(iterable, pred);
1✔
668
    }
669

670
    public boolean all(final Predicate<T> pred) {
671
        return every(iterable, pred);
1✔
672
    }
673

674
    public static <E> boolean some(final Iterable<E> iterable, final Predicate<E> pred) {
675
        Optional<E> optional = find(iterable, pred);
1✔
676
        return optional == null || optional.isPresent();
1✔
677
    }
678

679
    public boolean some(final Predicate<T> pred) {
680
        return some(iterable, pred);
1✔
681
    }
682

683
    /*
684
     * Documented, #any
685
     */
686
    public static <E> boolean any(final Iterable<E> iterable, final Predicate<E> pred) {
687
        return some(iterable, pred);
1✔
688
    }
689

690
    public boolean any(final Predicate<T> pred) {
691
        return some(iterable, pred);
1✔
692
    }
693

694
    public static <E> int count(final Iterable<E> iterable, final Predicate<E> pred) {
695
        int result = 0;
1✔
696
        for (E item : iterable) {
1✔
697
            if (pred.test(item)) {
1✔
698
                result += 1;
1✔
699
            }
700
        }
1✔
701
        return result;
1✔
702
    }
703

704
    public int count(final Predicate<T> pred) {
705
        return count(iterable, pred);
1✔
706
    }
707

708
    public static <E> boolean contains(final Iterable<E> iterable, final E elem) {
709
        return some(iterable, e -> Objects.equals(elem, e));
1✔
710
    }
711

712
    public boolean contains(final T elem) {
713
        return contains(iterable, elem);
1✔
714
    }
715

716
    public static <E> boolean containsWith(final Iterable<E> iterable, final E elem) {
717
        return some(
1✔
718
                iterable,
719
                e -> elem == null ? e == null : String.valueOf(e).contains(String.valueOf(elem)));
1✔
720
    }
721

722
    public boolean containsWith(final T elem) {
723
        return containsWith(iterable, elem);
1✔
724
    }
725

726
    public static <E> boolean contains(
727
            final Iterable<E> iterable, final E elem, final int fromIndex) {
728
        final List<E> list = newArrayList(iterable);
1✔
729
        return contains(list.subList(fromIndex, list.size()), elem);
1✔
730
    }
731

732
    public boolean containsAtLeast(final T value, final int count) {
733
        return Underscore.containsAtLeast(this.iterable, value, count);
1✔
734
    }
735

736
    public boolean containsAtMost(final T value, final int count) {
737
        return Underscore.containsAtMost(this.iterable, value, count);
1✔
738
    }
739

740
    public static <E> boolean containsAtLeast(
741
            final Iterable<E> iterable, final E value, final int count) {
742
        int foundItems = 0;
1✔
743
        for (E element : iterable) {
1✔
744
            if (Objects.equals(element, value)) {
1✔
745
                foundItems += 1;
1✔
746
            }
747
            if (foundItems >= count) {
1✔
748
                break;
1✔
749
            }
750
        }
1✔
751
        return foundItems >= count;
1✔
752
    }
753

754
    public static <E> boolean containsAtMost(
755
            final Iterable<E> iterable, final E value, final int count) {
756
        int foundItems = size(iterable);
1✔
757
        for (E element : iterable) {
1✔
758
            if (!(Objects.equals(element, value))) {
1✔
759
                foundItems -= 1;
1✔
760
            }
761
            if (foundItems <= count) {
1✔
762
                break;
1✔
763
            }
764
        }
1✔
765
        return foundItems <= count;
1✔
766
    }
767

768
    /*
769
     * Documented, #include
770
     */
771
    public static <E> boolean include(final Iterable<E> iterable, final E elem) {
772
        return contains(iterable, elem);
1✔
773
    }
774

775
    /*
776
     * Documented, #invoke
777
     */
778
    @SuppressWarnings("unchecked")
779
    public static <E> List<E> invoke(
780
            final Iterable<E> iterable, final String methodName, final List<Object> args) {
781
        final List<E> result = new ArrayList<>();
1✔
782
        final List<Class<?>> argTypes = map(args, Object::getClass);
1✔
783
        try {
784
            final Method method =
1✔
785
                    iterable.iterator()
1✔
786
                            .next()
1✔
787
                            .getClass()
1✔
788
                            .getMethod(methodName, argTypes.toArray(new Class[0]));
1✔
789
            for (E arg : iterable) {
1✔
790
                doInvoke(args, result, method, arg);
1✔
791
            }
1✔
792
        } catch (NoSuchMethodException e) {
1✔
793
            throw new IllegalArgumentException(e);
1✔
794
        }
1✔
795
        return result;
1✔
796
    }
797

798
    @SuppressWarnings("unchecked")
799
    private static <E> void doInvoke(List<Object> args, List<E> result, Method method, E arg) {
800
        try {
801
            result.add((E) method.invoke(arg, args.toArray(new Object[0])));
1✔
802
        } catch (Exception e) {
1✔
803
            throw new IllegalArgumentException(e);
1✔
804
        }
1✔
805
    }
1✔
806

807
    public List<T> invoke(final String methodName, final List<Object> args) {
808
        return invoke(iterable, methodName, args);
1✔
809
    }
810

811
    public static <E> List<E> invoke(final Iterable<E> iterable, final String methodName) {
812
        return invoke(iterable, methodName, Collections.emptyList());
1✔
813
    }
814

815
    public List<T> invoke(final String methodName) {
816
        return invoke(iterable, methodName);
1✔
817
    }
818

819
    /*
820
     * Documented, #pluck
821
     */
822
    public static <E> List<Object> pluck(final List<E> list, final String propertyName) {
823
        if (list.isEmpty()) {
1✔
824
            return Collections.emptyList();
1✔
825
        }
826
        return map(
1✔
827
                list,
828
                elem -> {
829
                    try {
830
                        return elem.getClass().getField(propertyName).get(elem);
1✔
831
                    } catch (Exception e) {
1✔
832
                        try {
833
                            return elem.getClass().getMethod(propertyName).invoke(elem);
1✔
834
                        } catch (Exception ex) {
1✔
835
                            throw new IllegalArgumentException(ex);
1✔
836
                        }
837
                    }
838
                });
839
    }
840

841
    public List<Object> pluck(final String propertyName) {
842
        return pluck(newArrayList(iterable), propertyName);
1✔
843
    }
844

845
    public static <E> Set<Object> pluck(final Set<E> set, final String propertyName) {
846
        if (set.isEmpty()) {
1✔
847
            return Collections.emptySet();
1✔
848
        }
849
        return map(
1✔
850
                set,
851
                elem -> {
852
                    try {
853
                        return elem.getClass().getField(propertyName).get(elem);
1✔
854
                    } catch (Exception e) {
1✔
855
                        try {
856
                            return elem.getClass().getMethod(propertyName).invoke(elem);
1✔
857
                        } catch (Exception ex) {
1✔
858
                            throw new IllegalArgumentException(ex);
1✔
859
                        }
860
                    }
861
                });
862
    }
863

864
    /*
865
     * Documented, #where
866
     */
867
    public static <T, E> List<E> where(
868
            final List<E> list, final List<Map.Entry<String, T>> properties) {
869
        return filter(list, new WherePredicate<>(properties));
1✔
870
    }
871

872
    public <E> List<T> where(final List<Map.Entry<String, E>> properties) {
873
        return where(newArrayList(iterable), properties);
1✔
874
    }
875

876
    public static <T, E> Set<E> where(
877
            final Set<E> set, final List<Map.Entry<String, T>> properties) {
878
        return filter(set, new WherePredicate<>(properties));
1✔
879
    }
880

881
    /*
882
     * Documented, #findWhere
883
     */
884
    public static <T, E> Optional<E> findWhere(
885
            final Iterable<E> iterable, final List<Map.Entry<String, T>> properties) {
886
        return find(iterable, new WherePredicate<>(properties));
1✔
887
    }
888

889
    public <E> Optional<T> findWhere(final List<Map.Entry<String, E>> properties) {
890
        return findWhere(iterable, properties);
1✔
891
    }
892

893
    /*
894
     * Documented, #max
895
     */
896
    public static <E extends Comparable<? super E>> E max(final Collection<E> collection) {
897
        return Collections.max(collection);
1✔
898
    }
899

900
    @SuppressWarnings("unchecked")
901
    public T max() {
902
        return (T) max((Collection) iterable);
1✔
903
    }
904

905
    @SuppressWarnings("unchecked")
906
    public static <E, F extends Comparable> E max(
907
            final Collection<E> collection, final Function<E, F> func) {
908
        return Collections.max(collection, (o1, o2) -> func.apply(o1).compareTo(func.apply(o2)));
1✔
909
    }
910

911
    @SuppressWarnings("unchecked")
912
    public <F extends Comparable<? super F>> T max(final Function<T, F> func) {
913
        return (T) max((Collection) iterable, func);
1✔
914
    }
915

916
    /*
917
     * Documented, #min
918
     */
919
    public static <E extends Comparable<? super E>> E min(final Collection<E> collection) {
920
        return Collections.min(collection);
1✔
921
    }
922

923
    @SuppressWarnings("unchecked")
924
    public T min() {
925
        return (T) min((Collection) iterable);
1✔
926
    }
927

928
    @SuppressWarnings("unchecked")
929
    public static <E, F extends Comparable> E min(
930
            final Collection<E> collection, final Function<E, F> func) {
931
        return Collections.min(collection, (o1, o2) -> func.apply(o1).compareTo(func.apply(o2)));
1✔
932
    }
933

934
    @SuppressWarnings("unchecked")
935
    public <F extends Comparable<? super F>> T min(final Function<T, F> func) {
936
        return (T) min((Collection) iterable, func);
1✔
937
    }
938

939
    /*
940
     * Documented, #shuffle
941
     */
942
    public static <E> List<E> shuffle(final Iterable<E> iterable) {
943
        final List<E> shuffled = newArrayList(iterable);
1✔
944
        Collections.shuffle(shuffled);
1✔
945
        return shuffled;
1✔
946
    }
947

948
    public List<T> shuffle() {
949
        return shuffle(iterable);
1✔
950
    }
951

952
    /*
953
     * Documented, #sample
954
     */
955
    public static <E> E sample(final Iterable<E> iterable) {
956
        return newArrayList(iterable).get(new java.security.SecureRandom().nextInt(size(iterable)));
1✔
957
    }
958

959
    public T sample() {
960
        return sample(iterable);
1✔
961
    }
962

963
    public static <E> Set<E> sample(final List<E> list, final int howMany) {
964
        final int size = Math.min(howMany, list.size());
1✔
965
        final Set<E> samples = newLinkedHashSetWithExpectedSize(size);
1✔
966
        while (samples.size() < size) {
1✔
967
            E sample = sample(list);
1✔
968
            samples.add(sample);
1✔
969
        }
1✔
970
        return samples;
1✔
971
    }
972

973
    public static <T extends Comparable<? super T>> List<T> sortWith(
974
            final Iterable<T> iterable, final Comparator<T> comparator) {
975
        final List<T> sortedList = newArrayList(iterable);
1✔
976
        sortedList.sort(comparator);
1✔
977
        return sortedList;
1✔
978
    }
979

980
    @SuppressWarnings("unchecked")
981
    public <E extends Comparable<? super E>> List<E> sortWith(final Comparator<E> comparator) {
982
        return sortWith((Iterable<E>) iterable, comparator);
1✔
983
    }
984

985
    /*
986
     * Documented, #sortBy
987
     */
988
    public static <E, T extends Comparable<? super T>> List<E> sortBy(
989
            final Iterable<E> iterable, final Function<E, T> func) {
990
        final List<E> sortedList = newArrayList(iterable);
1✔
991
        sortedList.sort(Comparator.comparing(func));
1✔
992
        return sortedList;
1✔
993
    }
994

995
    @SuppressWarnings("unchecked")
996
    public <E, V extends Comparable<? super V>> List<E> sortBy(final Function<E, V> func) {
997
        return sortBy((Iterable<E>) iterable, func);
1✔
998
    }
999

1000
    public static <K, V extends Comparable<? super V>> List<Map<K, V>> sortBy(
1001
            final Iterable<Map<K, V>> iterable, final K key) {
1002
        final List<Map<K, V>> sortedList = newArrayList(iterable);
1✔
1003
        sortedList.sort(Comparator.comparing(o -> o.get(key)));
1✔
1004
        return sortedList;
1✔
1005
    }
1006

1007
    /*
1008
     * Documented, #groupBy
1009
     */
1010
    public static <K, E> Map<K, List<E>> groupBy(
1011
            final Iterable<E> iterable, final Function<E, K> func) {
1012
        final Map<K, List<E>> retVal = new LinkedHashMap<>();
1✔
1013
        for (E e : iterable) {
1✔
1014
            final K key = func.apply(e);
1✔
1015
            List<E> val;
1016
            if (retVal.containsKey(key)) {
1✔
1017
                val = retVal.get(key);
1✔
1018
            } else {
1019
                val = new ArrayList<>();
1✔
1020
            }
1021
            val.add(e);
1✔
1022
            retVal.put(key, val);
1✔
1023
        }
1✔
1024
        return retVal;
1✔
1025
    }
1026

1027
    @SuppressWarnings("unchecked")
1028
    public <K, E> Map<K, List<E>> groupBy(final Function<E, K> func) {
1029
        return groupBy((Iterable<E>) iterable, func);
1✔
1030
    }
1031

1032
    public static <K, E> Map<K, Optional<E>> groupBy(
1033
            final Iterable<E> iterable,
1034
            final Function<E, K> func,
1035
            final BinaryOperator<E> binaryOperator) {
1036
        final Map<K, Optional<E>> retVal = new LinkedHashMap<>();
1✔
1037
        for (Map.Entry<K, List<E>> entry : groupBy(iterable, func).entrySet()) {
1✔
1038
            retVal.put(entry.getKey(), reduce(entry.getValue(), binaryOperator));
1✔
1039
        }
1✔
1040
        return retVal;
1✔
1041
    }
1042

1043
    @SuppressWarnings("unchecked")
1044
    public <K, E> Map<K, Optional<E>> groupBy(
1045
            final Function<E, K> func, final BinaryOperator<E> binaryOperator) {
1046
        return groupBy((Iterable<E>) iterable, func, binaryOperator);
1✔
1047
    }
1048

1049
    public static <K, E> Map<K, E> associateBy(
1050
            final Iterable<E> iterable, final Function<E, K> func) {
1051
        final Map<K, E> retVal = new LinkedHashMap<>();
1✔
1052
        for (E e : iterable) {
1✔
1053
            final K key = func.apply(e);
1✔
1054
            retVal.putIfAbsent(key, e);
1✔
1055
        }
1✔
1056
        return retVal;
1✔
1057
    }
1058

1059
    @SuppressWarnings("unchecked")
1060
    public <K, E> Map<K, E> associateBy(final Function<E, K> func) {
1061
        return associateBy((Iterable<E>) iterable, func);
1✔
1062
    }
1063

1064
    @SuppressWarnings("unchecked")
1065
    public static <K, E> Map<K, List<E>> indexBy(
1066
            final Iterable<E> iterable, final String property) {
1067
        return groupBy(
1✔
1068
                iterable,
1069
                elem -> {
1070
                    try {
1071
                        return (K) elem.getClass().getField(property).get(elem);
1✔
1072
                    } catch (Exception e) {
1✔
1073
                        return null;
1✔
1074
                    }
1075
                });
1076
    }
1077

1078
    @SuppressWarnings("unchecked")
1079
    public <K, E> Map<K, List<E>> indexBy(final String property) {
1080
        return indexBy((Iterable<E>) iterable, property);
1✔
1081
    }
1082

1083
    /*
1084
     * Documented, #countBy
1085
     */
1086
    public static <K, E> Map<K, Integer> countBy(final Iterable<E> iterable, Function<E, K> func) {
1087
        final Map<K, Integer> retVal = new LinkedHashMap<>();
1✔
1088
        for (E e : iterable) {
1✔
1089
            final K key = func.apply(e);
1✔
1090
            if (retVal.containsKey(key)) {
1✔
1091
                retVal.put(key, 1 + retVal.get(key));
1✔
1092
            } else {
1093
                retVal.put(key, 1);
1✔
1094
            }
1095
        }
1✔
1096
        return retVal;
1✔
1097
    }
1098

1099
    public static <K> Map<K, Integer> countBy(final Iterable<K> iterable) {
1100
        final Map<K, Integer> retVal = new LinkedHashMap<>();
1✔
1101
        for (K key : iterable) {
1✔
1102
            if (retVal.containsKey(key)) {
1✔
1103
                retVal.put(key, 1 + retVal.get(key));
1✔
1104
            } else {
1105
                retVal.put(key, 1);
1✔
1106
            }
1107
        }
1✔
1108
        return retVal;
1✔
1109
    }
1110

1111
    @SuppressWarnings("unchecked")
1112
    public <K, E> Map<K, Integer> countBy(Function<E, K> func) {
1113
        return countBy((Iterable<E>) iterable, func);
1✔
1114
    }
1115

1116
    @SuppressWarnings("unchecked")
1117
    public <K> Map<K, Integer> countBy() {
1118
        return countBy((Iterable<K>) iterable);
1✔
1119
    }
1120

1121
    /*
1122
     * Documented, #toArray
1123
     */
1124
    @SuppressWarnings("unchecked")
1125
    public static <E> E[] toArray(final Iterable<E> iterable) {
1126
        return (E[]) newArrayList(iterable).toArray();
1✔
1127
    }
1128

1129
    @SuppressWarnings("unchecked")
1130
    public <E> E[] toArray() {
1131
        return toArray((Iterable<E>) iterable);
1✔
1132
    }
1133

1134
    /*
1135
     * Documented, #toMap
1136
     */
1137
    public static <K, V> Map<K, V> toMap(final Iterable<Map.Entry<K, V>> iterable) {
1138
        final Map<K, V> result = new LinkedHashMap<>();
1✔
1139
        for (Map.Entry<K, V> entry : iterable) {
1✔
1140
            result.put(entry.getKey(), entry.getValue());
1✔
1141
        }
1✔
1142
        return result;
1✔
1143
    }
1144

1145
    @SuppressWarnings("unchecked")
1146
    public <K, V> Map<K, V> toMap() {
1147
        return toMap((Iterable<Map.Entry<K, V>>) iterable);
1✔
1148
    }
1149

1150
    public static <K, V> Map<K, V> toMap(final List<Map.Entry<K, V>> tuples) {
1151
        final Map<K, V> result = new LinkedHashMap<>();
1✔
1152
        for (final Map.Entry<K, V> entry : tuples) {
1✔
1153
            result.put(entry.getKey(), entry.getValue());
1✔
1154
        }
1✔
1155
        return result;
1✔
1156
    }
1157

1158
    public Map<T, Integer> toCardinalityMap() {
1159
        return toCardinalityMap(iterable);
1✔
1160
    }
1161

1162
    public static <K> Map<K, Integer> toCardinalityMap(final Iterable<K> iterable) {
1163
        Iterator<K> iterator = iterable.iterator();
1✔
1164
        Map<K, Integer> result = new LinkedHashMap<>();
1✔
1165

1166
        while (iterator.hasNext()) {
1✔
1167
            K item = iterator.next();
1✔
1168

1169
            if (result.containsKey(item)) {
1✔
1170
                result.put(item, result.get(item) + 1);
1✔
1171
            } else {
1172
                result.put(item, 1);
1✔
1173
            }
1174
        }
1✔
1175
        return result;
1✔
1176
    }
1177

1178
    /*
1179
     * Documented, #size
1180
     */
1181
    public static int size(final Iterable<?> iterable) {
1182
        if (iterable instanceof Collection) {
1✔
1183
            return ((Collection) iterable).size();
1✔
1184
        }
1185
        int size;
1186
        final Iterator<?> iterator = iterable.iterator();
1✔
1187
        for (size = 0; iterator.hasNext(); size += 1) {
1✔
1188
            iterator.next();
1✔
1189
        }
1190
        return size;
1✔
1191
    }
1192

1193
    public int size() {
1194
        return size(iterable);
1✔
1195
    }
1196

1197
    @SuppressWarnings("unchecked")
1198
    public static <E> int size(final E... array) {
1199
        return array.length;
1✔
1200
    }
1201

1202
    public static <E> List<List<E>> partition(final Iterable<E> iterable, final Predicate<E> pred) {
1203
        final List<E> retVal1 = new ArrayList<>();
1✔
1204
        final List<E> retVal2 = new ArrayList<>();
1✔
1205
        for (final E e : iterable) {
1✔
1206
            if (pred.test(e)) {
1✔
1207
                retVal1.add(e);
1✔
1208
            } else {
1209
                retVal2.add(e);
1✔
1210
            }
1211
        }
1✔
1212
        return Arrays.asList(retVal1, retVal2);
1✔
1213
    }
1214

1215
    @SuppressWarnings("unchecked")
1216
    public static <E> List<E>[] partition(final E[] iterable, final Predicate<E> pred) {
1217
        return partition(Arrays.asList(iterable), pred).toArray(new ArrayList[0]);
1✔
1218
    }
1219

1220
    public T singleOrNull() {
1221
        return singleOrNull(iterable);
1✔
1222
    }
1223

1224
    public T singleOrNull(Predicate<T> pred) {
1225
        return singleOrNull(iterable, pred);
1✔
1226
    }
1227

1228
    public static <E> E singleOrNull(final Iterable<E> iterable) {
1229
        Iterator<E> iterator = iterable.iterator();
1✔
1230
        if (!iterator.hasNext()) {
1✔
1231
            return null;
1✔
1232
        }
1233
        E result = iterator.next();
1✔
1234

1235
        if (iterator.hasNext()) {
1✔
1236
            result = null;
1✔
1237
        }
1238
        return result;
1✔
1239
    }
1240

1241
    public static <E> E singleOrNull(final Iterable<E> iterable, Predicate<E> pred) {
1242
        return singleOrNull(filter(iterable, pred));
1✔
1243
    }
1244

1245
    /*
1246
     * Documented, #first
1247
     */
1248
    public static <E> E first(final Iterable<E> iterable) {
1249
        return iterable.iterator().next();
1✔
1250
    }
1251

1252
    @SuppressWarnings("unchecked")
1253
    public static <E> E first(final E... array) {
1254
        return array[0];
1✔
1255
    }
1256

1257
    public static <E> List<E> first(final List<E> list, final int n) {
1258
        return list.subList(0, Math.min(n < 0 ? 0 : n, list.size()));
1✔
1259
    }
1260

1261
    public T first() {
1262
        return first(iterable);
1✔
1263
    }
1264

1265
    public List<T> first(final int n) {
1266
        return first(newArrayList(iterable), n);
1✔
1267
    }
1268

1269
    public static <E> E first(final Iterable<E> iterable, final Predicate<E> pred) {
1270
        return filter(newArrayList(iterable), pred).iterator().next();
1✔
1271
    }
1272

1273
    public static <E> List<E> first(
1274
            final Iterable<E> iterable, final Predicate<E> pred, final int n) {
1275
        List<E> list = filter(newArrayList(iterable), pred);
1✔
1276
        return list.subList(0, Math.min(n < 0 ? 0 : n, list.size()));
1✔
1277
    }
1278

1279
    public T first(final Predicate<T> pred) {
1280
        return first(newArrayList(iterable), pred);
1✔
1281
    }
1282

1283
    public List<T> first(final Predicate<T> pred, final int n) {
1284
        return first(newArrayList(iterable), pred, n);
1✔
1285
    }
1286

1287
    public static <E> E firstOrNull(final Iterable<E> iterable) {
1288
        final Iterator<E> iterator = iterable.iterator();
1✔
1289
        return iterator.hasNext() ? iterator.next() : null;
1✔
1290
    }
1291

1292
    public T firstOrNull() {
1293
        return firstOrNull(iterable);
1✔
1294
    }
1295

1296
    public static <E> E firstOrNull(final Iterable<E> iterable, final Predicate<E> pred) {
1297
        final Iterator<E> iterator = filter(newArrayList(iterable), pred).iterator();
1✔
1298
        return iterator.hasNext() ? iterator.next() : null;
1✔
1299
    }
1300

1301
    public T firstOrNull(final Predicate<T> pred) {
1302
        return firstOrNull(iterable, pred);
1✔
1303
    }
1304

1305
    public static <E> E head(final Iterable<E> iterable) {
1306
        return first(iterable);
1✔
1307
    }
1308

1309
    @SuppressWarnings("unchecked")
1310
    public static <E> E head(final E... array) {
1311
        return first(array);
1✔
1312
    }
1313

1314
    public static <E> List<E> head(final List<E> list, final int n) {
1315
        return first(list, n);
1✔
1316
    }
1317

1318
    public T head() {
1319
        return first();
1✔
1320
    }
1321

1322
    public List<T> head(final int n) {
1323
        return first(n);
1✔
1324
    }
1325

1326
    /*
1327
     * Documented, #initial
1328
     */
1329
    public static <E> List<E> initial(final List<E> list) {
1330
        return initial(list, 1);
1✔
1331
    }
1332

1333
    public static <E> List<E> initial(final List<E> list, final int n) {
1334
        return list.subList(0, Math.max(0, list.size() - n));
1✔
1335
    }
1336

1337
    @SuppressWarnings("unchecked")
1338
    public static <E> E[] initial(final E... array) {
1339
        return initial(array, 1);
1✔
1340
    }
1341

1342
    public static <E> E[] initial(final E[] array, final int n) {
1343
        return Arrays.copyOf(array, array.length - n);
1✔
1344
    }
1345

1346
    public List<T> initial() {
1347
        return initial((List<T>) iterable, 1);
1✔
1348
    }
1349

1350
    public List<T> initial(final int n) {
1351
        return initial((List<T>) iterable, n);
1✔
1352
    }
1353

1354
    @SuppressWarnings("unchecked")
1355
    public static <E> E last(final E... array) {
1356
        return array[array.length - 1];
1✔
1357
    }
1358

1359
    /*
1360
     * Documented, #last
1361
     */
1362
    public static <E> E last(final List<E> list) {
1363
        return list.get(list.size() - 1);
1✔
1364
    }
1365

1366
    public static <E> List<E> last(final List<E> list, final int n) {
1367
        return list.subList(Math.max(0, list.size() - n), list.size());
1✔
1368
    }
1369

1370
    public T last() {
1371
        return last((List<T>) iterable);
1✔
1372
    }
1373

1374
    public List<T> last(final int n) {
1375
        return last((List<T>) iterable, n);
1✔
1376
    }
1377

1378
    public static <E> E last(final List<E> list, final Predicate<E> pred) {
1379
        final List<E> filteredList = filter(list, pred);
1✔
1380
        return filteredList.get(filteredList.size() - 1);
1✔
1381
    }
1382

1383
    public T last(final Predicate<T> pred) {
1384
        return last((List<T>) iterable, pred);
1✔
1385
    }
1386

1387
    public static <E> E lastOrNull(final List<E> list) {
1388
        return list.isEmpty() ? null : list.get(list.size() - 1);
1✔
1389
    }
1390

1391
    public T lastOrNull() {
1392
        return lastOrNull((List<T>) iterable);
1✔
1393
    }
1394

1395
    public static <E> E lastOrNull(final List<E> list, final Predicate<E> pred) {
1396
        final List<E> filteredList = filter(list, pred);
1✔
1397
        return filteredList.isEmpty() ? null : filteredList.get(filteredList.size() - 1);
1✔
1398
    }
1399

1400
    public T lastOrNull(final Predicate<T> pred) {
1401
        return lastOrNull((List<T>) iterable, pred);
1✔
1402
    }
1403

1404
    /*
1405
     * Documented, #rest
1406
     */
1407
    public static <E> List<E> rest(final List<E> list) {
1408
        return rest(list, 1);
1✔
1409
    }
1410

1411
    public static <E> List<E> rest(final List<E> list, int n) {
1412
        return list.subList(Math.min(n, list.size()), list.size());
1✔
1413
    }
1414

1415
    @SuppressWarnings("unchecked")
1416
    public static <E> E[] rest(final E... array) {
1417
        return rest(array, 1);
1✔
1418
    }
1419

1420
    @SuppressWarnings("unchecked")
1421
    public static <E> E[] rest(final E[] array, final int n) {
1422
        return (E[]) rest(Arrays.asList(array), n).toArray();
1✔
1423
    }
1424

1425
    public List<T> rest() {
1426
        return rest((List<T>) iterable);
1✔
1427
    }
1428

1429
    public List<T> rest(int n) {
1430
        return rest((List<T>) iterable, n);
1✔
1431
    }
1432

1433
    public static <E> List<E> tail(final List<E> list) {
1434
        return rest(list);
1✔
1435
    }
1436

1437
    public static <E> List<E> tail(final List<E> list, final int n) {
1438
        return rest(list, n);
1✔
1439
    }
1440

1441
    @SuppressWarnings("unchecked")
1442
    public static <E> E[] tail(final E... array) {
1443
        return rest(array);
1✔
1444
    }
1445

1446
    public static <E> E[] tail(final E[] array, final int n) {
1447
        return rest(array, n);
1✔
1448
    }
1449

1450
    public List<T> tail() {
1451
        return rest();
1✔
1452
    }
1453

1454
    public List<T> tail(final int n) {
1455
        return rest(n);
1✔
1456
    }
1457

1458
    public static <E> List<E> drop(final List<E> list) {
1459
        return rest(list);
1✔
1460
    }
1461

1462
    public static <E> List<E> drop(final List<E> list, final int n) {
1463
        return rest(list, n);
1✔
1464
    }
1465

1466
    @SuppressWarnings("unchecked")
1467
    public static <E> E[] drop(final E... array) {
1468
        return rest(array);
1✔
1469
    }
1470

1471
    public static <E> E[] drop(final E[] array, final int n) {
1472
        return rest(array, n);
1✔
1473
    }
1474

1475
    /*
1476
     * Documented, #compact
1477
     */
1478
    public static <E> List<E> compact(final List<E> list) {
1479
        return filter(
1✔
1480
                list,
1481
                arg ->
1482
                        !String.valueOf(arg).equals("null")
1✔
1483
                                && !String.valueOf(arg).equals("0")
1✔
1484
                                && !String.valueOf(arg).equals("false")
1✔
1485
                                && !String.valueOf(arg).equals(""));
1✔
1486
    }
1487

1488
    @SuppressWarnings("unchecked")
1489
    public static <E> E[] compact(final E... array) {
1490
        return (E[]) compact(Arrays.asList(array)).toArray();
1✔
1491
    }
1492

1493
    public static <E> List<E> compact(final List<E> list, final E falsyValue) {
1494
        return filter(list, arg -> !(Objects.equals(arg, falsyValue)));
1✔
1495
    }
1496

1497
    @SuppressWarnings("unchecked")
1498
    public static <E> E[] compact(final E[] array, final E falsyValue) {
1499
        return (E[]) compact(Arrays.asList(array), falsyValue).toArray();
1✔
1500
    }
1501

1502
    public List<T> compact() {
1503
        return compact((List<T>) iterable);
1✔
1504
    }
1505

1506
    public List<T> compact(final T falsyValue) {
1507
        return compact((List<T>) iterable, falsyValue);
1✔
1508
    }
1509

1510
    /*
1511
     * Documented, #flatten
1512
     */
1513
    public static <E> List<E> flatten(final List<?> list) {
1514
        List<E> flattened = new ArrayList<>();
1✔
1515
        flatten(list, flattened, -1);
1✔
1516
        return flattened;
1✔
1517
    }
1518

1519
    public static <E> List<E> flatten(final List<?> list, final boolean shallow) {
1520
        List<E> flattened = new ArrayList<>();
1✔
1521
        flatten(list, flattened, shallow ? 1 : -1);
1✔
1522
        return flattened;
1✔
1523
    }
1524

1525
    @SuppressWarnings("unchecked")
1526
    private static <E> void flatten(
1527
            final List<?> fromTreeList, final List<E> toFlatList, final int shallowLevel) {
1528
        for (Object item : fromTreeList) {
1✔
1529
            if (item instanceof List<?> && shallowLevel != 0) {
1✔
1530
                flatten((List<?>) item, toFlatList, shallowLevel - 1);
1✔
1531
            } else {
1532
                toFlatList.add((E) item);
1✔
1533
            }
1534
        }
1✔
1535
    }
1✔
1536

1537
    public List<T> flatten() {
1538
        return flatten((List<T>) iterable);
1✔
1539
    }
1540

1541
    public List<T> flatten(final boolean shallow) {
1542
        return flatten((List<T>) iterable, shallow);
1✔
1543
    }
1544

1545
    /*
1546
     * Documented, #without
1547
     */
1548
    @SuppressWarnings("unchecked")
1549
    public static <E> List<E> without(final List<E> list, E... values) {
1550
        final List<E> valuesList = Arrays.asList(values);
1✔
1551
        return filter(list, elem -> !contains(valuesList, elem));
1✔
1552
    }
1553

1554
    @SuppressWarnings("unchecked")
1555
    public static <E> E[] without(final E[] array, final E... values) {
1556
        return (E[]) without(Arrays.asList(array), values).toArray();
1✔
1557
    }
1558

1559
    /*
1560
     * Documented, #uniq
1561
     */
1562
    public static <E> List<E> uniq(final List<E> list) {
1563
        return newArrayList(newLinkedHashSet(list));
1✔
1564
    }
1565

1566
    @SuppressWarnings("unchecked")
1567
    public static <E> E[] uniq(final E... array) {
1568
        return (E[]) uniq(Arrays.asList(array)).toArray();
1✔
1569
    }
1570

1571
    public static <K, E> Collection<E> uniq(final Iterable<E> iterable, final Function<E, K> func) {
1572
        final Map<K, E> retVal = new LinkedHashMap<>();
1✔
1573
        for (final E e : iterable) {
1✔
1574
            final K key = func.apply(e);
1✔
1575
            retVal.put(key, e);
1✔
1576
        }
1✔
1577
        return retVal.values();
1✔
1578
    }
1579

1580
    @SuppressWarnings("unchecked")
1581
    public static <K, E> E[] uniq(final E[] array, final Function<E, K> func) {
1582
        return (E[]) uniq(Arrays.asList(array), func).toArray();
1✔
1583
    }
1584

1585
    public static <E> List<E> distinct(final List<E> list) {
1586
        return uniq(list);
1✔
1587
    }
1588

1589
    @SuppressWarnings("unchecked")
1590
    public static <E> E[] distinct(final E... array) {
1591
        return uniq(array);
1✔
1592
    }
1593

1594
    public static <K, E> Collection<E> distinctBy(
1595
            final Iterable<E> iterable, final Function<E, K> func) {
1596
        return uniq(iterable, func);
1✔
1597
    }
1598

1599
    public static <K, E> E[] distinctBy(final E[] array, final Function<E, K> func) {
1600
        return uniq(array, func);
1✔
1601
    }
1602

1603
    /*
1604
     * Documented, #union
1605
     */
1606
    @SuppressWarnings("unchecked")
1607
    public static <E> List<E> union(final List<E> list, final List<E>... lists) {
1608
        final Set<E> union = new LinkedHashSet<>();
1✔
1609
        union.addAll(list);
1✔
1610
        for (List<E> localList : lists) {
1✔
1611
            union.addAll(localList);
1✔
1612
        }
1613
        return newArrayList(union);
1✔
1614
    }
1615

1616
    @SuppressWarnings("unchecked")
1617
    public List<T> unionWith(final List<T>... lists) {
1618
        return union(newArrayList(iterable), lists);
1✔
1619
    }
1620

1621
    @SuppressWarnings("unchecked")
1622
    public static <E> E[] union(final E[]... arrays) {
1623
        final Set<E> union = new LinkedHashSet<>();
1✔
1624
        for (E[] array : arrays) {
1✔
1625
            union.addAll(Arrays.asList(array));
1✔
1626
        }
1627
        return (E[]) newArrayList(union).toArray();
1✔
1628
    }
1629

1630
    /*
1631
     * Documented, #intersection
1632
     */
1633
    public static <E> List<E> intersection(final List<E> list1, final List<E> list2) {
1634
        final List<E> result = new ArrayList<>();
1✔
1635
        for (final E item : list1) {
1✔
1636
            if (list2.contains(item)) {
1✔
1637
                result.add(item);
1✔
1638
            }
1639
        }
1✔
1640
        return result;
1✔
1641
    }
1642

1643
    @SuppressWarnings("unchecked")
1644
    public static <E> List<E> intersection(final List<E> list, final List<E>... lists) {
1645
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1646
        stack.push(list);
1✔
1647
        for (List<E> es : lists) {
1✔
1648
            stack.push(intersection(stack.peek(), es));
1✔
1649
        }
1650
        return stack.peek();
1✔
1651
    }
1652

1653
    @SuppressWarnings("unchecked")
1654
    public List<T> intersectionWith(final List<T>... lists) {
1655
        return intersection(newArrayList(iterable), lists);
1✔
1656
    }
1657

1658
    @SuppressWarnings("unchecked")
1659
    public static <E> E[] intersection(final E[]... arrays) {
1660
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1661
        stack.push(Arrays.asList(arrays[0]));
1✔
1662
        for (int index = 1; index < arrays.length; index += 1) {
1✔
1663
            stack.push(intersection(stack.peek(), Arrays.asList(arrays[index])));
1✔
1664
        }
1665
        return (E[]) stack.peek().toArray();
1✔
1666
    }
1667

1668
    /*
1669
     * Documented, #difference
1670
     */
1671
    public static <E> List<E> difference(final List<E> list1, final List<E> list2) {
1672
        final List<E> result = new ArrayList<>();
1✔
1673
        for (final E item : list1) {
1✔
1674
            if (!list2.contains(item)) {
1✔
1675
                result.add(item);
1✔
1676
            }
1677
        }
1✔
1678
        return result;
1✔
1679
    }
1680

1681
    @SuppressWarnings("unchecked")
1682
    public static <E> List<E> difference(final List<E> list, final List<E>... lists) {
1683
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1684
        stack.push(list);
1✔
1685
        for (List<E> es : lists) {
1✔
1686
            stack.push(difference(stack.peek(), es));
1✔
1687
        }
1688
        return stack.peek();
1✔
1689
    }
1690

1691
    @SuppressWarnings("unchecked")
1692
    public List<T> differenceWith(final List<T>... lists) {
1693
        return difference(newArrayList(iterable), lists);
1✔
1694
    }
1695

1696
    @SuppressWarnings("unchecked")
1697
    public static <E> E[] difference(final E[]... arrays) {
1698
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1699
        stack.push(Arrays.asList(arrays[0]));
1✔
1700
        for (int index = 1; index < arrays.length; index += 1) {
1✔
1701
            stack.push(difference(stack.peek(), Arrays.asList(arrays[index])));
1✔
1702
        }
1703
        return (E[]) stack.peek().toArray();
1✔
1704
    }
1705

1706
    /*
1707
     * Documented, #zip
1708
     */
1709
    @SuppressWarnings("unchecked")
1710
    public static <T> List<List<T>> zip(final List<T>... lists) {
1711
        final List<List<T>> zipped = new ArrayList<>();
1✔
1712
        each(
1✔
1713
                Arrays.asList(lists),
1✔
1714
                list -> {
1715
                    int index = 0;
1✔
1716
                    for (T elem : list) {
1✔
1717
                        final List<T> nTuple;
1718
                        nTuple = index >= zipped.size() ? new ArrayList<>() : zipped.get(index);
1✔
1719
                        if (index >= zipped.size()) {
1✔
1720
                            zipped.add(nTuple);
1✔
1721
                        }
1722
                        index += 1;
1✔
1723
                        nTuple.add(elem);
1✔
1724
                    }
1✔
1725
                });
1✔
1726
        return zipped;
1✔
1727
    }
1728

1729
    @SuppressWarnings("unchecked")
1730
    public static <T> List<List<T>> unzip(final List<T>... lists) {
1731
        final List<List<T>> unzipped = new ArrayList<>();
1✔
1732
        for (int index = 0; index < lists[0].size(); index += 1) {
1✔
1733
            final List<T> nTuple = new ArrayList<>();
1✔
1734
            for (List<T> list : lists) {
1✔
1735
                nTuple.add(list.get(index));
1✔
1736
            }
1737
            unzipped.add(nTuple);
1✔
1738
        }
1739
        return unzipped;
1✔
1740
    }
1741

1742
    /*
1743
     * Documented, #object
1744
     */
1745
    public static <K, V> List<Map.Entry<K, V>> object(final List<K> keys, final List<V> values) {
1746
        return map(
1✔
1747
                keys,
1748
                new Function<>() {
1✔
1749
                    private int index;
1750

1751
                    @Override
1752
                    public Map.Entry<K, V> apply(K key) {
1753
                        return Map.entry(key, values.get(index++));
1✔
1754
                    }
1755
                });
1756
    }
1757

1758
    public static <E> int findIndex(final List<E> list, final Predicate<E> pred) {
1759
        for (int index = 0; index < list.size(); index++) {
1✔
1760
            if (pred.test(list.get(index))) {
1✔
1761
                return index;
1✔
1762
            }
1763
        }
1764
        return -1;
1✔
1765
    }
1766

1767
    public static <E> int findIndex(final E[] array, final Predicate<E> pred) {
1768
        return findIndex(Arrays.asList(array), pred);
1✔
1769
    }
1770

1771
    public static <E> int findLastIndex(final List<E> list, final Predicate<E> pred) {
1772
        for (int index = list.size() - 1; index >= 0; index--) {
1✔
1773
            if (pred.test(list.get(index))) {
1✔
1774
                return index;
1✔
1775
            }
1776
        }
1777
        return -1;
1✔
1778
    }
1779

1780
    public static <E> int findLastIndex(final E[] array, final Predicate<E> pred) {
1781
        return findLastIndex(Arrays.asList(array), pred);
1✔
1782
    }
1783

1784
    public static <E extends Comparable<E>> int binarySearch(
1785
            final Iterable<E> iterable, final E key) {
1786
        if (key == null) {
1✔
1787
            return first(iterable) == null ? 0 : -1;
1✔
1788
        }
1789
        int begin = 0;
1✔
1790
        int end = size(iterable) - 1;
1✔
1791
        int numberOfNullValues = 0;
1✔
1792
        List<E> list = new ArrayList<>();
1✔
1793
        for (E item : iterable) {
1✔
1794
            if (item == null) {
1✔
1795
                numberOfNullValues++;
1✔
1796
                end--;
1✔
1797
            } else {
1798
                list.add(item);
1✔
1799
            }
1800
        }
1✔
1801
        while (begin <= end) {
1✔
1802
            int middle = begin + (end - begin) / 2;
1✔
1803
            if (key.compareTo(list.get(middle)) < 0) {
1✔
1804
                end = middle - 1;
1✔
1805
            } else if (key.compareTo(list.get(middle)) > 0) {
1✔
1806
                begin = middle + 1;
1✔
1807
            } else {
1808
                return middle + numberOfNullValues;
1✔
1809
            }
1810
        }
1✔
1811
        return -(begin + numberOfNullValues + 1);
1✔
1812
    }
1813

1814
    public static <E extends Comparable<E>> int binarySearch(final E[] array, final E key) {
1815
        return binarySearch(Arrays.asList(array), key);
1✔
1816
    }
1817

1818
    /*
1819
     * Documented, #sortedIndex
1820
     */
1821
    public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value) {
1822
        int index = 0;
1✔
1823
        for (E elem : list) {
1✔
1824
            if (elem.compareTo(value) >= 0) {
1✔
1825
                return index;
1✔
1826
            }
1827
            index += 1;
1✔
1828
        }
1✔
1829
        return -1;
1✔
1830
    }
1831

1832
    public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value) {
1833
        return sortedIndex(Arrays.asList(array), value);
1✔
1834
    }
1835

1836
    @SuppressWarnings("unchecked")
1837
    public static <E extends Comparable<E>> int sortedIndex(
1838
            final List<E> list, final E value, final String propertyName) {
1839
        try {
1840
            final Field property = value.getClass().getField(propertyName);
1✔
1841
            final Object valueProperty = property.get(value);
1✔
1842
            int index = 0;
1✔
1843
            for (E elem : list) {
1✔
1844
                if (((Comparable) property.get(elem)).compareTo(valueProperty) >= 0) {
1✔
1845
                    return index;
1✔
1846
                }
1847
                index += 1;
1✔
1848
            }
1✔
1849
            return -1;
1✔
1850
        } catch (Exception e) {
1✔
1851
            throw new IllegalArgumentException(e);
1✔
1852
        }
1853
    }
1854

1855
    public static <E extends Comparable<E>> int sortedIndex(
1856
            final E[] array, final E value, final String propertyName) {
1857
        return sortedIndex(Arrays.asList(array), value, propertyName);
1✔
1858
    }
1859

1860
    /*
1861
     * Documented, #indexOf
1862
     */
1863
    public static <E> int indexOf(final List<E> list, final E value) {
1864
        return list.indexOf(value);
1✔
1865
    }
1866

1867
    public static <E> int indexOf(final E[] array, final E value) {
1868
        return indexOf(Arrays.asList(array), value);
1✔
1869
    }
1870

1871
    /*
1872
     * Documented, #lastIndexOf
1873
     */
1874
    public static <E> int lastIndexOf(final List<E> list, final E value) {
1875
        return list.lastIndexOf(value);
1✔
1876
    }
1877

1878
    public static <E> int lastIndexOf(final E[] array, final E value) {
1879
        return lastIndexOf(Arrays.asList(array), value);
1✔
1880
    }
1881

1882
    /*
1883
     * Documented, #range
1884
     */
1885
    public static List<Integer> range(int stop) {
1886
        return range(0, stop, 1);
1✔
1887
    }
1888

1889
    public static List<Integer> range(int start, int stop) {
1890
        return range(start, stop, start < stop ? 1 : -1);
1✔
1891
    }
1892

1893
    public static List<Integer> range(int start, int stop, int step) {
1894
        List<Integer> list = new ArrayList<>();
1✔
1895
        if (step == 0) {
1✔
1896
            return list;
1✔
1897
        }
1898
        if (start < stop) {
1✔
1899
            for (int value = start; value < stop; value += step) {
1✔
1900
                list.add(value);
1✔
1901
            }
1902
        } else {
1903
            for (int value = start; value > stop; value += step) {
1✔
1904
                list.add(value);
1✔
1905
            }
1906
        }
1907
        return list;
1✔
1908
    }
1909

1910
    public static List<Character> range(char stop) {
1911
        return range('a', stop, 1);
1✔
1912
    }
1913

1914
    public static List<Character> range(char start, char stop) {
1915
        return range(start, stop, start < stop ? 1 : -1);
1✔
1916
    }
1917

1918
    public static List<Character> range(char start, char stop, int step) {
1919
        List<Character> list = new ArrayList<>();
1✔
1920
        if (step == 0) {
1✔
1921
            return list;
1✔
1922
        }
1923
        if (start < stop) {
1✔
1924
            for (char value = start; value < stop; value += step) {
1✔
1925
                list.add(value);
1✔
1926
            }
1927
        } else {
1928
            for (char value = start; value > stop; value += step) {
1✔
1929
                list.add(value);
1✔
1930
            }
1931
        }
1932
        return list;
1✔
1933
    }
1934

1935
    public static <T> List<List<T>> chunk(final Iterable<T> iterable, final int size) {
1936
        if (size <= 0) {
1✔
1937
            return new ArrayList<>();
1✔
1938
        }
1939
        return chunk(iterable, size, size);
1✔
1940
    }
1941

1942
    public static <T> List<List<T>> chunk(
1943
            final Iterable<T> iterable, final int size, final int step) {
1944
        if (step <= 0 || size < 0) {
1✔
1945
            return new ArrayList<>();
1✔
1946
        }
1947
        int index = 0;
1✔
1948
        int length = size(iterable);
1✔
1949
        final List<List<T>> result = new ArrayList<>(size == 0 ? size : (length / size) + 1);
1✔
1950
        while (index < length) {
1✔
1951
            result.add(newArrayList(iterable).subList(index, Math.min(length, index + size)));
1✔
1952
            index += step;
1✔
1953
        }
1954
        return result;
1✔
1955
    }
1956

1957
    public static <T> List<List<T>> chunkFill(
1958
            final Iterable<T> iterable, final int size, final T fillValue) {
1959
        if (size <= 0) {
1✔
1960
            return new ArrayList<>();
1✔
1961
        }
1962
        return chunkFill(iterable, size, size, fillValue);
1✔
1963
    }
1964

1965
    public static <T> List<List<T>> chunkFill(
1966
            final Iterable<T> iterable, final int size, final int step, final T fillValue) {
1967
        if (step <= 0 || size < 0) {
1✔
1968
            return new ArrayList<>();
1✔
1969
        }
1970
        final List<List<T>> result = chunk(iterable, size, step);
1✔
1971
        int difference = size - result.get(result.size() - 1).size();
1✔
1972
        for (int i = difference; 0 < i; i--) {
1✔
1973
            result.get(result.size() - 1).add(fillValue);
1✔
1974
        }
1975
        return result;
1✔
1976
    }
1977

1978
    public List<List<T>> chunk(final int size) {
1979
        return chunk(getIterable(), size, size);
1✔
1980
    }
1981

1982
    public List<List<T>> chunk(final int size, final int step) {
1983
        return chunk(getIterable(), size, step);
1✔
1984
    }
1985

1986
    public List<List<T>> chunkFill(final int size, final T fillvalue) {
1987
        return chunkFill(getIterable(), size, size, fillvalue);
1✔
1988
    }
1989

1990
    public List<List<T>> chunkFill(final int size, final int step, T fillvalue) {
1991
        return chunkFill(getIterable(), size, step, fillvalue);
1✔
1992
    }
1993

1994
    public static <T> List<T> cycle(final Iterable<T> iterable, final int times) {
1995
        int size = Math.abs(size(iterable) * times);
1✔
1996
        if (size == 0) {
1✔
1997
            return new ArrayList<>();
1✔
1998
        }
1999
        List<T> list = newArrayListWithExpectedSize(size);
1✔
2000
        int round = 0;
1✔
2001
        if (times > 0) {
1✔
2002
            while (round < times) {
1✔
2003
                for (T element : iterable) {
1✔
2004
                    list.add(element);
1✔
2005
                }
1✔
2006
                round++;
1✔
2007
            }
2008
        } else {
2009
            list = cycle(Underscore.reverse(iterable), -times);
1✔
2010
        }
2011
        return list;
1✔
2012
    }
2013

2014
    public List<T> cycle(final int times) {
2015
        return cycle(value(), times);
1✔
2016
    }
2017

2018
    public static <T> List<T> repeat(final T element, final int times) {
2019
        if (times <= 0) {
1✔
2020
            return new ArrayList<>();
1✔
2021
        }
2022
        List<T> result = newArrayListWithExpectedSize(times);
1✔
2023
        for (int i = 0; i < times; i++) {
1✔
2024
            result.add(element);
1✔
2025
        }
2026
        return result;
1✔
2027
    }
2028

2029
    public static <T> List<T> interpose(final Iterable<T> iterable, final T interElement) {
2030
        if (interElement == null) {
1✔
2031
            return newArrayList(iterable);
1✔
2032
        }
2033
        int size = size(iterable);
1✔
2034
        int index = 0;
1✔
2035
        List<T> array = newArrayListWithExpectedSize(size * 2);
1✔
2036
        for (T elem : iterable) {
1✔
2037
            array.add(elem);
1✔
2038
            if (index + 1 < size) {
1✔
2039
                array.add(interElement);
1✔
2040
                index++;
1✔
2041
            }
2042
        }
1✔
2043
        return array;
1✔
2044
    }
2045

2046
    public static <T> List<T> interposeByList(
2047
            final Iterable<T> iterable, final Iterable<T> interIter) {
2048
        if (interIter == null) {
1✔
2049
            return newArrayList(iterable);
1✔
2050
        }
2051
        List<T> interList = newArrayList(interIter);
1✔
2052
        if (isEmpty(interIter)) {
1✔
2053
            return newArrayList(iterable);
1✔
2054
        }
2055
        int size = size(iterable);
1✔
2056
        List<T> array = newArrayListWithExpectedSize(size + interList.size());
1✔
2057
        int index = 0;
1✔
2058
        for (T element : iterable) {
1✔
2059
            array.add(element);
1✔
2060
            if (index < interList.size() && index + 1 < size) {
1✔
2061
                array.add(interList.get(index));
1✔
2062
                index++;
1✔
2063
            }
2064
        }
1✔
2065
        return array;
1✔
2066
    }
2067

2068
    public List<T> interpose(final T element) {
2069
        return interpose(value(), element);
1✔
2070
    }
2071

2072
    public List<T> interposeByList(final Iterable<T> interIter) {
2073
        return interposeByList(value(), interIter);
1✔
2074
    }
2075

2076
    /*
2077
     * Documented, #bind
2078
     */
2079
    public static <T, F> Function<F, T> bind(final Function<F, T> function) {
2080
        return function;
1✔
2081
    }
2082

2083
    /*
2084
     * Documented, #memoize
2085
     */
2086
    public static <T, F> Function<F, T> memoize(final Function<F, T> function) {
2087
        return new MemoizeFunction<>() {
1✔
2088
            @Override
2089
            public T calc(F arg) {
2090
                return function.apply(arg);
1✔
2091
            }
2092
        };
2093
    }
2094

2095
    /*
2096
     * Documented, #delay
2097
     */
2098
    public static <T> java.util.concurrent.ScheduledFuture<T> delay(
2099
            final Supplier<T> function, final int delayMilliseconds) {
2100
        final java.util.concurrent.ScheduledExecutorService scheduler =
2101
                java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
1✔
2102
        final java.util.concurrent.ScheduledFuture<T> future =
1✔
2103
                scheduler.schedule(
1✔
2104
                        function::get,
1✔
2105
                        delayMilliseconds,
2106
                        java.util.concurrent.TimeUnit.MILLISECONDS);
2107
        scheduler.shutdown();
1✔
2108
        return future;
1✔
2109
    }
2110

2111
    public static <T> java.util.concurrent.ScheduledFuture<T> defer(final Supplier<T> function) {
2112
        return delay(function, 0);
1✔
2113
    }
2114

2115
    public static java.util.concurrent.ScheduledFuture<Void> defer(final Runnable runnable) {
2116
        return delay(
1✔
2117
                () -> {
2118
                    runnable.run();
1✔
2119
                    return null;
1✔
2120
                },
2121
                0);
2122
    }
2123

2124
    public static <T> Supplier<T> throttle(final Supplier<T> function, final int waitMilliseconds) {
2125
        class ThrottleLater implements Supplier<T> {
2126
            private final Supplier<T> localFunction;
2127
            private java.util.concurrent.ScheduledFuture<T> timeout;
2128
            private long previous;
2129

2130
            ThrottleLater(final Supplier<T> function) {
1✔
2131
                this.localFunction = function;
1✔
2132
            }
1✔
2133

2134
            @Override
2135
            public T get() {
2136
                previous = now();
1✔
2137
                timeout = null;
1✔
2138
                return localFunction.get();
1✔
2139
            }
2140

2141
            java.util.concurrent.ScheduledFuture<T> getTimeout() {
2142
                return timeout;
1✔
2143
            }
2144

2145
            void setTimeout(java.util.concurrent.ScheduledFuture<T> timeout) {
2146
                this.timeout = timeout;
1✔
2147
            }
1✔
2148

2149
            long getPrevious() {
2150
                return previous;
1✔
2151
            }
2152

2153
            void setPrevious(long previous) {
2154
                this.previous = previous;
1✔
2155
            }
1✔
2156
        }
2157

2158
        class ThrottleFunction implements Supplier<T> {
2159
            private final Supplier<T> localFunction;
2160
            private final ThrottleLater throttleLater;
2161

2162
            ThrottleFunction(final Supplier<T> function) {
1✔
2163
                this.localFunction = function;
1✔
2164
                this.throttleLater = new ThrottleLater(function);
1✔
2165
            }
1✔
2166

2167
            @Override
2168
            public T get() {
2169
                final long now = now();
1✔
2170
                if (throttleLater.getPrevious() == 0L) {
1✔
2171
                    throttleLater.setPrevious(now);
1✔
2172
                }
2173
                final long remaining = waitMilliseconds - (now - throttleLater.getPrevious());
1✔
2174
                T result = null;
1✔
2175
                if (remaining <= 0) {
1✔
2176
                    throttleLater.setPrevious(now);
1✔
2177
                    result = localFunction.get();
1✔
2178
                } else if (throttleLater.getTimeout() == null) {
1✔
2179
                    throttleLater.setTimeout(delay(throttleLater, waitMilliseconds));
1✔
2180
                }
2181
                return result;
1✔
2182
            }
2183
        }
2184
        return new ThrottleFunction(function);
1✔
2185
    }
2186

2187
    /*
2188
     * Documented, #debounce
2189
     */
2190
    public static <T> Supplier<T> debounce(
2191
            final Supplier<T> function, final int delayMilliseconds) {
2192
        return new Supplier<>() {
1✔
2193
            private java.util.concurrent.ScheduledFuture<T> timeout;
2194

2195
            @Override
2196
            public T get() {
2197
                clearTimeout(timeout);
1✔
2198
                timeout = delay(function, delayMilliseconds);
1✔
2199
                return null;
1✔
2200
            }
2201
        };
2202
    }
2203

2204
    /*
2205
     * Documented, #wrap
2206
     */
2207
    public static <T> Function<Void, T> wrap(
2208
            final UnaryOperator<T> function, final Function<UnaryOperator<T>, T> wrapper) {
2209
        return arg -> wrapper.apply(function);
1✔
2210
    }
2211

2212
    public static <E> Predicate<E> negate(final Predicate<E> pred) {
2213
        return item -> !pred.test(item);
1✔
2214
    }
2215

2216
    /*
2217
     * Documented, #compose
2218
     */
2219
    @SuppressWarnings("unchecked")
2220
    public static <T> Function<T, T> compose(final Function<T, T>... func) {
2221
        return arg -> {
1✔
2222
            T result = arg;
1✔
2223
            for (int index = func.length - 1; index >= 0; index -= 1) {
1✔
2224
                result = func[index].apply(result);
1✔
2225
            }
2226
            return result;
1✔
2227
        };
2228
    }
2229

2230
    /*
2231
     * Documented, #after
2232
     */
2233
    public static <E> Supplier<E> after(final int count, final Supplier<E> function) {
2234
        class AfterFunction implements Supplier<E> {
2235
            private final int count;
2236
            private final Supplier<E> localFunction;
2237
            private int index;
2238
            private E result;
2239

2240
            AfterFunction(final int count, final Supplier<E> function) {
1✔
2241
                this.count = count;
1✔
2242
                this.localFunction = function;
1✔
2243
            }
1✔
2244

2245
            public E get() {
2246
                if (++index >= count) {
1✔
2247
                    result = localFunction.get();
1✔
2248
                }
2249
                return result;
1✔
2250
            }
2251
        }
2252
        return new AfterFunction(count, function);
1✔
2253
    }
2254

2255
    /*
2256
     * Documented, #before
2257
     */
2258
    public static <E> Supplier<E> before(final int count, final Supplier<E> function) {
2259
        class BeforeFunction implements Supplier<E> {
2260
            private final int count;
2261
            private final Supplier<E> localFunction;
2262
            private int index;
2263
            private E result;
2264

2265
            BeforeFunction(final int count, final Supplier<E> function) {
1✔
2266
                this.count = count;
1✔
2267
                this.localFunction = function;
1✔
2268
            }
1✔
2269

2270
            public E get() {
2271
                if (++index <= count) {
1✔
2272
                    result = localFunction.get();
1✔
2273
                }
2274
                return result;
1✔
2275
            }
2276
        }
2277
        return new BeforeFunction(count, function);
1✔
2278
    }
2279

2280
    /*
2281
     * Documented, #once
2282
     */
2283
    public static <T> Supplier<T> once(final Supplier<T> function) {
2284
        return new Supplier<>() {
1✔
2285
            private volatile boolean executed;
2286
            private T result;
2287

2288
            @Override
2289
            public T get() {
2290
                if (!executed) {
1✔
2291
                    executed = true;
1✔
2292
                    result = function.get();
1✔
2293
                }
2294
                return result;
1✔
2295
            }
2296
        };
2297
    }
2298

2299
    /*
2300
     * Documented, #keys
2301
     */
2302
    public static <K, V> Set<K> keys(final Map<K, V> object) {
2303
        return object.keySet();
1✔
2304
    }
2305

2306
    /*
2307
     * Documented, #values
2308
     */
2309
    public static <K, V> Collection<V> values(final Map<K, V> object) {
2310
        return object.values();
1✔
2311
    }
2312

2313
    public static <K, V> List<Map.Entry<K, V>> mapObject(
2314
            final Map<K, V> object, final Function<? super V, V> func) {
2315
        return map(
1✔
2316
                newArrayList(object.entrySet()),
1✔
2317
                entry -> Map.entry(entry.getKey(), func.apply(entry.getValue())));
1✔
2318
    }
2319

2320
    /*
2321
     * Documented, #pairs
2322
     */
2323
    public static <K, V> List<Map.Entry<K, V>> pairs(final Map<K, V> object) {
2324
        return map(
1✔
2325
                newArrayList(object.entrySet()),
1✔
2326
                entry -> Map.entry(entry.getKey(), entry.getValue()));
1✔
2327
    }
2328

2329
    /*
2330
     * Documented, #invert
2331
     */
2332
    public static <K, V> List<Map.Entry<V, K>> invert(final Map<K, V> object) {
2333
        return map(
1✔
2334
                newArrayList(object.entrySet()),
1✔
2335
                entry -> Map.entry(entry.getValue(), entry.getKey()));
1✔
2336
    }
2337

2338
    /*
2339
     * Documented, #functions
2340
     */
2341
    public static List<String> functions(final Object object) {
2342
        final List<String> result = new ArrayList<>();
1✔
2343
        for (final Method method : object.getClass().getDeclaredMethods()) {
1✔
2344
            result.add(method.getName());
1✔
2345
        }
2346
        return sort(uniq(result));
1✔
2347
    }
2348

2349
    public static List<String> methods(final Object object) {
2350
        return functions(object);
1✔
2351
    }
2352

2353
    /*
2354
     * Documented, #extend
2355
     */
2356
    @SuppressWarnings("unchecked")
2357
    public static <K, V> Map<K, V> extend(final Map<K, V> destination, final Map<K, V>... sources) {
2358
        final Map<K, V> result = new LinkedHashMap<>();
1✔
2359
        result.putAll(destination);
1✔
2360
        for (final Map<K, V> source : sources) {
1✔
2361
            result.putAll(source);
1✔
2362
        }
2363
        return result;
1✔
2364
    }
2365

2366
    public static <E> E findKey(final List<E> list, final Predicate<E> pred) {
2367
        for (E e : list) {
1✔
2368
            if (pred.test(e)) {
1✔
2369
                return e;
1✔
2370
            }
2371
        }
1✔
2372
        return null;
1✔
2373
    }
2374

2375
    public static <E> E findKey(final E[] array, final Predicate<E> pred) {
2376
        return findKey(Arrays.asList(array), pred);
1✔
2377
    }
2378

2379
    public static <E> E findLastKey(final List<E> list, final Predicate<E> pred) {
2380
        for (int index = list.size() - 1; index >= 0; index--) {
1✔
2381
            if (pred.test(list.get(index))) {
1✔
2382
                return list.get(index);
1✔
2383
            }
2384
        }
2385
        return null;
1✔
2386
    }
2387

2388
    public static <E> E findLastKey(final E[] array, final Predicate<E> pred) {
2389
        return findLastKey(Arrays.asList(array), pred);
1✔
2390
    }
2391

2392
    /*
2393
     * Documented, #pick
2394
     */
2395
    @SuppressWarnings("unchecked")
2396
    public static <K, V> List<Map.Entry<K, V>> pick(final Map<K, V> object, final K... keys) {
2397
        return without(
1✔
2398
                map(
1✔
2399
                        newArrayList(object.entrySet()),
1✔
2400
                        entry -> {
2401
                            if (Arrays.asList(keys).contains(entry.getKey())) {
1✔
2402
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2403
                            } else {
2404
                                return null;
1✔
2405
                            }
2406
                        }),
2407
                (Map.Entry<K, V>) null);
2408
    }
2409

2410
    @SuppressWarnings("unchecked")
2411
    public static <K, V> List<Map.Entry<K, V>> pick(
2412
            final Map<K, V> object, final Predicate<V> pred) {
2413
        return without(
1✔
2414
                map(
1✔
2415
                        newArrayList(object.entrySet()),
1✔
2416
                        entry -> {
2417
                            if (pred.test(object.get(entry.getKey()))) {
1✔
2418
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2419
                            } else {
2420
                                return null;
1✔
2421
                            }
2422
                        }),
2423
                (Map.Entry<K, V>) null);
2424
    }
2425

2426
    /*
2427
     * Documented, #omit
2428
     */
2429
    @SuppressWarnings("unchecked")
2430
    public static <K, V> List<Map.Entry<K, V>> omit(final Map<K, V> object, final K... keys) {
2431
        return without(
1✔
2432
                map(
1✔
2433
                        newArrayList(object.entrySet()),
1✔
2434
                        entry -> {
2435
                            if (Arrays.asList(keys).contains(entry.getKey())) {
1✔
2436
                                return null;
1✔
2437
                            } else {
2438
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2439
                            }
2440
                        }),
2441
                (Map.Entry<K, V>) null);
2442
    }
2443

2444
    @SuppressWarnings("unchecked")
2445
    public static <K, V> List<Map.Entry<K, V>> omit(
2446
            final Map<K, V> object, final Predicate<V> pred) {
2447
        return without(
1✔
2448
                map(
1✔
2449
                        newArrayList(object.entrySet()),
1✔
2450
                        entry -> {
2451
                            if (pred.test(entry.getValue())) {
1✔
2452
                                return null;
1✔
2453
                            } else {
2454
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2455
                            }
2456
                        }),
2457
                (Map.Entry<K, V>) null);
2458
    }
2459

2460
    /*
2461
     * Documented, #defaults
2462
     */
2463
    public static <K, V> Map<K, V> defaults(final Map<K, V> object, final Map<K, V> defaults) {
2464
        final Map<K, V> result = new LinkedHashMap<>();
1✔
2465
        result.putAll(defaults);
1✔
2466
        result.putAll(object);
1✔
2467
        return result;
1✔
2468
    }
2469

2470
    /*
2471
     * Documented, #clone
2472
     */
2473
    public static Object clone(final Object obj) {
2474
        try {
2475
            if (obj instanceof Cloneable) {
1✔
2476
                for (final Method method : obj.getClass().getMethods()) {
1✔
2477
                    if (method.getName().equals("clone")
1✔
2478
                            && method.getParameterTypes().length == 0) {
1✔
2479
                        return method.invoke(obj);
1✔
2480
                    }
2481
                }
2482
            }
2483
        } catch (Exception e) {
1✔
2484
            throw new IllegalArgumentException(e);
1✔
2485
        }
1✔
2486
        throw new IllegalArgumentException("Cannot clone object");
1✔
2487
    }
2488

2489
    @SuppressWarnings("unchecked")
2490
    public static <E> E[] clone(final E... iterable) {
2491
        return Arrays.copyOf(iterable, iterable.length);
1✔
2492
    }
2493

2494
    public static <T> void tap(final Iterable<T> iterable, final Consumer<? super T> func) {
2495
        each(iterable, func);
1✔
2496
    }
1✔
2497

2498
    public static <K, V> boolean isMatch(final Map<K, V> object, final Map<K, V> properties) {
2499
        for (final K key : keys(properties)) {
1✔
2500
            if (!object.containsKey(key) || !object.get(key).equals(properties.get(key))) {
1✔
2501
                return false;
1✔
2502
            }
2503
        }
1✔
2504
        return true;
1✔
2505
    }
2506

2507
    /*
2508
     * Documented, #isEqual
2509
     */
2510
    public static boolean isEqual(final Object object, final Object other) {
2511
        return Objects.equals(object, other);
1✔
2512
    }
2513

2514
    public static <K, V> boolean isEmpty(final Map<K, V> object) {
2515
        return object == null || object.isEmpty();
1✔
2516
    }
2517

2518
    /*
2519
     * Documented, #isEmpty
2520
     */
2521
    public static <T> boolean isEmpty(final Iterable<T> iterable) {
2522
        return iterable == null || !iterable.iterator().hasNext();
1✔
2523
    }
2524

2525
    public boolean isEmpty() {
2526
        return iterable == null || !iterable.iterator().hasNext();
1✔
2527
    }
2528

2529
    public static <K, V> boolean isNotEmpty(final Map<K, V> object) {
2530
        return object != null && !object.isEmpty();
1✔
2531
    }
2532

2533
    public static <T> boolean isNotEmpty(final Iterable<T> iterable) {
2534
        return iterable != null && iterable.iterator().hasNext();
1✔
2535
    }
2536

2537
    public boolean isNotEmpty() {
2538
        return iterable != null && iterable.iterator().hasNext();
1✔
2539
    }
2540

2541
    /*
2542
     * Documented, #isArray
2543
     */
2544
    public static boolean isArray(final Object object) {
2545
        return object != null && object.getClass().isArray();
1✔
2546
    }
2547

2548
    /*
2549
     * Documented, #isObject
2550
     */
2551
    public static boolean isObject(final Object object) {
2552
        return object instanceof Map;
1✔
2553
    }
2554

2555
    /*
2556
     * Documented, #isFunction
2557
     */
2558
    public static boolean isFunction(final Object object) {
2559
        return object instanceof Function;
1✔
2560
    }
2561

2562
    /*
2563
     * Documented, #isString
2564
     */
2565
    public static boolean isString(final Object object) {
2566
        return object instanceof String;
1✔
2567
    }
2568

2569
    /*
2570
     * Documented, #isNumber
2571
     */
2572
    public static boolean isNumber(final Object object) {
2573
        return object instanceof Number;
1✔
2574
    }
2575

2576
    /*
2577
     * Documented, #isDate
2578
     */
2579
    public static boolean isDate(final Object object) {
2580
        return object instanceof Date;
1✔
2581
    }
2582

2583
    public static boolean isRegExp(final Object object) {
2584
        return object instanceof java.util.regex.Pattern;
1✔
2585
    }
2586

2587
    public static boolean isError(final Object object) {
2588
        return object instanceof Throwable;
1✔
2589
    }
2590

2591
    /*
2592
     * Documented, #isBoolean
2593
     */
2594
    public static boolean isBoolean(final Object object) {
2595
        return object instanceof Boolean;
1✔
2596
    }
2597

2598
    public static boolean isNull(final Object object) {
2599
        return object == null;
1✔
2600
    }
2601

2602
    /*
2603
     * Documented, #has
2604
     */
2605
    public static <K, V> boolean has(final Map<K, V> object, final K key) {
2606
        return object.containsKey(key);
1✔
2607
    }
2608

2609
    public static <E> E identity(final E value) {
2610
        return value;
1✔
2611
    }
2612

2613
    public static <E> Supplier<E> constant(final E value) {
2614
        return () -> value;
1✔
2615
    }
2616

2617
    public static <K, V> Function<Map<K, V>, V> property(final K key) {
2618
        return object -> object.get(key);
1✔
2619
    }
2620

2621
    public static <K, V> Function<K, V> propertyOf(final Map<K, V> object) {
2622
        return object::get;
1✔
2623
    }
2624

2625
    public static <K, V> Predicate<Map<K, V>> matcher(final Map<K, V> object) {
2626
        return item -> {
1✔
2627
            for (final K key : keys(object)) {
1✔
2628
                if (!item.containsKey(key) || !item.get(key).equals(object.get(key))) {
1✔
2629
                    return false;
1✔
2630
                }
2631
            }
1✔
2632
            return true;
1✔
2633
        };
2634
    }
2635

2636
    /*
2637
     * Documented, #times
2638
     */
2639
    public static void times(final int count, final Runnable runnable) {
2640
        for (int index = 0; index < count; index += 1) {
1✔
2641
            runnable.run();
1✔
2642
        }
2643
    }
1✔
2644

2645
    /*
2646
     * Documented, #random
2647
     */
2648
    public static int random(final int min, final int max) {
2649
        return min + new java.security.SecureRandom().nextInt(max - min + 1);
1✔
2650
    }
2651

2652
    public static int random(final int max) {
2653
        return new java.security.SecureRandom().nextInt(max + 1);
1✔
2654
    }
2655

2656
    public static long now() {
2657
        return new Date().getTime();
1✔
2658
    }
2659

2660
    /*
2661
     * Documented, #escape
2662
     */
2663
    public static String escape(final String value) {
2664
        final StringBuilder builder = new StringBuilder();
1✔
2665
        for (final char ch : value.toCharArray()) {
1✔
2666
            builder.append(ESCAPES.containsKey(ch) ? ESCAPES.get(ch) : ch);
1✔
2667
        }
2668
        return builder.toString();
1✔
2669
    }
2670

2671
    public static String unescape(final String value) {
2672
        return value.replace("&#x60;", "`")
1✔
2673
                .replace("&#x27;", "'")
1✔
2674
                .replace("&lt;", "<")
1✔
2675
                .replace("&gt;", ">")
1✔
2676
                .replace("&quot;", "\"")
1✔
2677
                .replace("&amp;", "&");
1✔
2678
    }
2679

2680
    /*
2681
     * Documented, #result
2682
     */
2683
    public static <E> Object result(final Iterable<E> iterable, final Predicate<E> pred) {
2684
        for (E element : iterable) {
1✔
2685
            if (pred.test(element)) {
1✔
2686
                if (element instanceof Map.Entry) {
1✔
2687
                    if (((Map.Entry) element).getValue() instanceof Supplier) {
1✔
2688
                        return ((Supplier) ((Map.Entry) element).getValue()).get();
1✔
2689
                    }
2690
                    return ((Map.Entry) element).getValue();
1✔
2691
                }
2692
                return element;
1✔
2693
            }
2694
        }
1✔
2695
        return null;
1✔
2696
    }
2697

2698
    /*
2699
     * Documented, #uniqueId
2700
     */
2701
    public static String uniqueId(final String prefix) {
2702
        return (prefix == null ? "" : prefix) + UNIQUE_ID.incrementAndGet();
1✔
2703
    }
2704

2705
    /*
2706
     * Documented, #uniquePassword
2707
     */
2708
    public static String uniquePassword() {
2709
        final String[] passwords =
1✔
2710
                new String[] {
2711
                    "ALKJVBPIQYTUIWEBVPQALZVKQRWORTUYOYISHFLKAJMZNXBVMNFGAHKJSDFALAPOQIERIUYTGSFGKMZNXBVJAHGFAKX",
2712
                    "1234567890",
2713
                    "qpowiealksdjzmxnvbfghsdjtreiuowiruksfhksajmzxncbvlaksjdhgqwetytopskjhfgvbcnmzxalksjdfhgbvzm",
2714
                    ".@,-+/()#$%^&*!"
2715
                };
2716
        final StringBuilder result = new StringBuilder();
1✔
2717
        final long passwordLength =
2718
                Math.abs(UUID.randomUUID().getLeastSignificantBits() % MIN_PASSWORD_LENGTH_8)
1✔
2719
                        + MIN_PASSWORD_LENGTH_8;
2720
        for (int index = 0; index < passwordLength; index += 1) {
1✔
2721
            final int passIndex = (int) (passwords.length * (long) index / passwordLength);
1✔
2722
            final int charIndex =
2723
                    (int)
2724
                            Math.abs(
1✔
2725
                                    UUID.randomUUID().getLeastSignificantBits()
1✔
2726
                                            % passwords[passIndex].length());
1✔
2727
            result.append(passwords[passIndex].charAt(charIndex));
1✔
2728
        }
2729
        return result.toString();
1✔
2730
    }
2731

2732
    public static <K, V> Template<Map<K, V>> template(final String template) {
2733
        return new TemplateImpl<>(template);
1✔
2734
    }
2735

2736
    public static String format(final String template, final Object... params) {
2737
        final java.util.regex.Matcher matcher = FORMAT_PATTERN.matcher(template);
1✔
2738
        final StringBuffer buffer = new StringBuffer();
1✔
2739
        int index = 0;
1✔
2740
        while (matcher.find()) {
1✔
2741
            if (matcher.group(1).isEmpty()) {
1✔
2742
                matcher.appendReplacement(buffer, "<%" + index++ + "%>");
1✔
2743
            } else {
2744
                matcher.appendReplacement(buffer, "<%" + matcher.group(1) + "%>");
1✔
2745
            }
2746
        }
2747
        matcher.appendTail(buffer);
1✔
2748
        final String newTemplate = buffer.toString();
1✔
2749
        final Map<Integer, String> args = new LinkedHashMap<>();
1✔
2750
        index = 0;
1✔
2751
        for (Object param : params) {
1✔
2752
            args.put(index, param.toString());
1✔
2753
            index += 1;
1✔
2754
        }
2755
        return new TemplateImpl<Integer, String>(newTemplate).apply(args);
1✔
2756
    }
2757

2758
    public static <T> Iterable<T> iterate(final T seed, final UnaryOperator<T> unaryOperator) {
2759
        return new MyIterable<>(seed, unaryOperator);
1✔
2760
    }
2761

2762
    /*
2763
     * Documented, #chain
2764
     */
2765
    public static <T> Chain<T> chain(final List<T> list) {
2766
        return new Underscore.Chain<>(list);
1✔
2767
    }
2768

2769
    public static Chain<Map<String, Object>> chain(final Map<String, Object> map) {
2770
        return new Underscore.Chain<>(map);
1✔
2771
    }
2772

2773
    public static <T> Chain<T> chain(final Iterable<T> iterable) {
2774
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2775
    }
2776

2777
    public static <T> Chain<T> chain(final Iterable<T> iterable, int size) {
2778
        return new Underscore.Chain<>(newArrayList(iterable, size));
1✔
2779
    }
2780

2781
    @SuppressWarnings("unchecked")
2782
    public static <T> Chain<T> chain(final T... array) {
2783
        return new Underscore.Chain<>(Arrays.asList(array));
1✔
2784
    }
2785

2786
    public static Chain<Integer> chain(final int[] array) {
2787
        return new Underscore.Chain<>(newIntegerList(array));
1✔
2788
    }
2789

2790
    public Chain<T> chain() {
2791
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2792
    }
2793

2794
    public static <T> Chain<T> of(final List<T> list) {
2795
        return new Underscore.Chain<>(list);
1✔
2796
    }
2797

2798
    public static <T> Chain<T> of(final Iterable<T> iterable) {
2799
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2800
    }
2801

2802
    public static <T> Chain<T> of(final Iterable<T> iterable, int size) {
2803
        return new Underscore.Chain<>(newArrayList(iterable, size));
1✔
2804
    }
2805

2806
    @SuppressWarnings("unchecked")
2807
    public static <T> Chain<T> of(final T... array) {
2808
        return new Underscore.Chain<>(Arrays.asList(array));
1✔
2809
    }
2810

2811
    public static Chain<Integer> of(final int[] array) {
2812
        return new Underscore.Chain<>(newIntegerList(array));
1✔
2813
    }
2814

2815
    public Chain<T> of() {
2816
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2817
    }
2818

2819
    public static class Chain<T> {
2820
        private final T item;
2821
        private final List<T> list;
2822
        private final Map<String, Object> map;
2823

2824
        public Chain(final T item) {
1✔
2825
            this.item = item;
1✔
2826
            this.list = null;
1✔
2827
            this.map = null;
1✔
2828
        }
1✔
2829

2830
        public Chain(final List<T> list) {
1✔
2831
            this.item = null;
1✔
2832
            this.list = list;
1✔
2833
            this.map = null;
1✔
2834
        }
1✔
2835

2836
        public Chain(final Map<String, Object> map) {
1✔
2837
            this.item = null;
1✔
2838
            this.list = null;
1✔
2839
            this.map = map;
1✔
2840
        }
1✔
2841

2842
        public Chain<T> first() {
2843
            return new Chain<>(Underscore.first(list));
1✔
2844
        }
2845

2846
        public Chain<T> first(int n) {
2847
            return new Chain<>(Underscore.first(list, n));
1✔
2848
        }
2849

2850
        public Chain<T> first(final Predicate<T> pred) {
2851
            return new Chain<>(Underscore.first(list, pred));
1✔
2852
        }
2853

2854
        public Chain<T> first(final Predicate<T> pred, int n) {
2855
            return new Chain<>(Underscore.first(list, pred, n));
1✔
2856
        }
2857

2858
        public Chain<T> firstOrNull() {
2859
            return new Chain<>(Underscore.firstOrNull(list));
1✔
2860
        }
2861

2862
        public Chain<T> firstOrNull(final Predicate<T> pred) {
2863
            return new Chain<>(Underscore.firstOrNull(list, pred));
1✔
2864
        }
2865

2866
        public Chain<T> initial() {
2867
            return new Chain<>(Underscore.initial(list));
1✔
2868
        }
2869

2870
        public Chain<T> initial(int n) {
2871
            return new Chain<>(Underscore.initial(list, n));
1✔
2872
        }
2873

2874
        public Chain<T> last() {
2875
            return new Chain<>(Underscore.last(list));
1✔
2876
        }
2877

2878
        public Chain<T> last(int n) {
2879
            return new Chain<>(Underscore.last(list, n));
1✔
2880
        }
2881

2882
        public Chain<T> lastOrNull() {
2883
            return new Chain<>(Underscore.lastOrNull(list));
1✔
2884
        }
2885

2886
        public Chain<T> lastOrNull(final Predicate<T> pred) {
2887
            return new Chain<>(Underscore.lastOrNull(list, pred));
1✔
2888
        }
2889

2890
        public Chain<T> rest() {
2891
            return new Chain<>(Underscore.rest(list));
1✔
2892
        }
2893

2894
        public Chain<T> rest(int n) {
2895
            return new Chain<>(Underscore.rest(list, n));
1✔
2896
        }
2897

2898
        public Chain<T> compact() {
2899
            return new Chain<>(Underscore.compact(list));
1✔
2900
        }
2901

2902
        public Chain<T> compact(final T falsyValue) {
2903
            return new Chain<>(Underscore.compact(list, falsyValue));
1✔
2904
        }
2905

2906
        @SuppressWarnings("unchecked")
2907
        public Chain flatten() {
2908
            return new Chain<>(Underscore.flatten(list));
1✔
2909
        }
2910

2911
        public <F> Chain<F> map(final Function<? super T, F> func) {
2912
            return new Chain<>(Underscore.map(list, func));
1✔
2913
        }
2914

2915
        public <F> Chain<F> mapMulti(final BiConsumer<? super T, ? super Consumer<F>> mapper) {
2916
            return new Chain<>(Underscore.mapMulti(list, mapper));
1✔
2917
        }
2918

2919
        public <F> Chain<F> mapIndexed(final BiFunction<Integer, ? super T, F> func) {
2920
            return new Chain<>(Underscore.mapIndexed(list, func));
1✔
2921
        }
2922

2923
        public Chain<T> replace(final Predicate<T> pred, final T value) {
2924
            return new Chain<>(Underscore.replace(list, pred, value));
1✔
2925
        }
2926

2927
        public Chain<T> replaceIndexed(final PredicateIndexed<T> pred, final T value) {
2928
            return new Chain<>(Underscore.replaceIndexed(list, pred, value));
1✔
2929
        }
2930

2931
        public Chain<T> filter(final Predicate<T> pred) {
2932
            return new Chain<>(Underscore.filter(list, pred));
1✔
2933
        }
2934

2935
        public Chain<T> filterIndexed(final PredicateIndexed<T> pred) {
2936
            return new Chain<>(Underscore.filterIndexed(list, pred));
1✔
2937
        }
2938

2939
        public Chain<T> reject(final Predicate<T> pred) {
2940
            return new Chain<>(Underscore.reject(list, pred));
1✔
2941
        }
2942

2943
        public Chain<T> rejectIndexed(final PredicateIndexed<T> pred) {
2944
            return new Chain<>(Underscore.rejectIndexed(list, pred));
1✔
2945
        }
2946

2947
        public Chain<T> filterFalse(final Predicate<T> pred) {
2948
            return new Chain<>(Underscore.reject(list, pred));
1✔
2949
        }
2950

2951
        public <F> Chain<F> reduce(final BiFunction<F, T, F> func, final F zeroElem) {
2952
            return new Chain<>(Underscore.reduce(list, func, zeroElem));
1✔
2953
        }
2954

2955
        public Chain<Optional<T>> reduce(final BinaryOperator<T> func) {
2956
            return new Chain<>(Underscore.reduce(list, func));
1✔
2957
        }
2958

2959
        public <F> Chain<F> reduceRight(final BiFunction<F, T, F> func, final F zeroElem) {
2960
            return new Chain<>(Underscore.reduceRight(list, func, zeroElem));
1✔
2961
        }
2962

2963
        public Chain<Optional<T>> reduceRight(final BinaryOperator<T> func) {
2964
            return new Chain<>(Underscore.reduceRight(list, func));
1✔
2965
        }
2966

2967
        public Chain<Optional<T>> find(final Predicate<T> pred) {
2968
            return new Chain<>(Underscore.find(list, pred));
1✔
2969
        }
2970

2971
        public Chain<Optional<T>> findLast(final Predicate<T> pred) {
2972
            return new Chain<>(Underscore.findLast(list, pred));
1✔
2973
        }
2974

2975
        @SuppressWarnings("unchecked")
2976
        public Chain<Comparable> max() {
2977
            return new Chain<>(Underscore.max((Collection) list));
1✔
2978
        }
2979

2980
        public <F extends Comparable<? super F>> Chain<T> max(final Function<T, F> func) {
2981
            return new Chain<>(Underscore.max(list, func));
1✔
2982
        }
2983

2984
        @SuppressWarnings("unchecked")
2985
        public Chain<Comparable> min() {
2986
            return new Chain<>(Underscore.min((Collection) list));
1✔
2987
        }
2988

2989
        public <F extends Comparable<? super F>> Chain<T> min(final Function<T, F> func) {
2990
            return new Chain<>(Underscore.min(list, func));
1✔
2991
        }
2992

2993
        @SuppressWarnings("unchecked")
2994
        public Chain<Comparable> sort() {
2995
            return new Chain<>(Underscore.sort((List<Comparable>) list));
1✔
2996
        }
2997

2998
        @SuppressWarnings("unchecked")
2999
        public <F extends Comparable<? super F>> Chain<F> sortWith(final Comparator<F> comparator) {
3000
            return new Chain<>(Underscore.sortWith((List<F>) list, comparator));
1✔
3001
        }
3002

3003
        public <F extends Comparable<? super F>> Chain<T> sortBy(final Function<T, F> func) {
3004
            return new Chain<>(Underscore.sortBy(list, func));
1✔
3005
        }
3006

3007
        @SuppressWarnings("unchecked")
3008
        public <K> Chain<Map<K, Comparable>> sortBy(final K key) {
3009
            return new Chain<>(Underscore.sortBy((List<Map<K, Comparable>>) list, key));
1✔
3010
        }
3011

3012
        public <F> Chain<Map<F, List<T>>> groupBy(final Function<T, F> func) {
3013
            return new Chain<>(Underscore.groupBy(list, func));
1✔
3014
        }
3015

3016
        public <F> Chain<Map<F, T>> associateBy(final Function<T, F> func) {
3017
            return new Chain<>(Underscore.associateBy(list, func));
1✔
3018
        }
3019

3020
        public <F> Chain<Map<F, Optional<T>>> groupBy(
3021
                final Function<T, F> func, final BinaryOperator<T> binaryOperator) {
3022
            return new Chain<>(Underscore.groupBy(list, func, binaryOperator));
1✔
3023
        }
3024

3025
        public Chain<Map<Object, List<T>>> indexBy(final String property) {
3026
            return new Chain<>(Underscore.indexBy(list, property));
1✔
3027
        }
3028

3029
        public <F> Chain<Map<F, Integer>> countBy(final Function<T, F> func) {
3030
            return new Chain<>(Underscore.countBy(list, func));
1✔
3031
        }
3032

3033
        public Chain<Map<T, Integer>> countBy() {
3034
            return new Chain<>(Underscore.countBy(list));
1✔
3035
        }
3036

3037
        public Chain<T> shuffle() {
3038
            return new Chain<>(Underscore.shuffle(list));
1✔
3039
        }
3040

3041
        public Chain<T> sample() {
3042
            return new Chain<>(Underscore.sample(list));
1✔
3043
        }
3044

3045
        public Chain<T> sample(final int howMany) {
3046
            return new Chain<>(Underscore.newArrayList(Underscore.sample(list, howMany)));
1✔
3047
        }
3048

3049
        public Chain<T> tap(final Consumer<T> func) {
3050
            Underscore.each(list, func);
1✔
3051
            return new Chain<>(list);
1✔
3052
        }
3053

3054
        public Chain<T> forEach(final Consumer<T> func) {
3055
            return tap(func);
1✔
3056
        }
3057

3058
        public Chain<T> forEachRight(final Consumer<T> func) {
3059
            Underscore.eachRight(list, func);
1✔
3060
            return new Chain<>(list);
1✔
3061
        }
3062

3063
        public Chain<Boolean> every(final Predicate<T> pred) {
3064
            return new Chain<>(Underscore.every(list, pred));
1✔
3065
        }
3066

3067
        public Chain<Boolean> some(final Predicate<T> pred) {
3068
            return new Chain<>(Underscore.some(list, pred));
1✔
3069
        }
3070

3071
        public Chain<Integer> count(final Predicate<T> pred) {
3072
            return new Chain<>(Underscore.count(list, pred));
1✔
3073
        }
3074

3075
        public Chain<Boolean> contains(final T elem) {
3076
            return new Chain<>(Underscore.contains(list, elem));
1✔
3077
        }
3078

3079
        public Chain<Boolean> containsWith(final T elem) {
3080
            return new Chain<>(Underscore.containsWith(list, elem));
1✔
3081
        }
3082

3083
        public Chain<T> invoke(final String methodName, final List<Object> args) {
3084
            return new Chain<>(Underscore.invoke(list, methodName, args));
1✔
3085
        }
3086

3087
        public Chain<T> invoke(final String methodName) {
3088
            return new Chain<>(Underscore.invoke(list, methodName));
1✔
3089
        }
3090

3091
        public Chain<Object> pluck(final String propertyName) {
3092
            return new Chain<>(Underscore.pluck(list, propertyName));
1✔
3093
        }
3094

3095
        public <E> Chain<T> where(final List<Map.Entry<String, E>> properties) {
3096
            return new Chain<>(Underscore.where(list, properties));
1✔
3097
        }
3098

3099
        public <E> Chain<Optional<T>> findWhere(final List<Map.Entry<String, E>> properties) {
3100
            return new Chain<>(Underscore.findWhere(list, properties));
1✔
3101
        }
3102

3103
        public Chain<T> uniq() {
3104
            return new Chain<>(Underscore.uniq(list));
1✔
3105
        }
3106

3107
        public <F> Chain<T> uniq(final Function<T, F> func) {
3108
            return new Chain<>(Underscore.newArrayList(Underscore.uniq(list, func)));
1✔
3109
        }
3110

3111
        public Chain<T> distinct() {
3112
            return new Chain<>(Underscore.uniq(list));
1✔
3113
        }
3114

3115
        @SuppressWarnings("unchecked")
3116
        public <F> Chain<F> distinctBy(final Function<T, F> func) {
3117
            return new Chain<>(Underscore.newArrayList((Iterable<F>) Underscore.uniq(list, func)));
1✔
3118
        }
3119

3120
        @SuppressWarnings("unchecked")
3121
        public Chain<T> union(final List<T>... lists) {
3122
            return new Chain<>(Underscore.union(list, lists));
1✔
3123
        }
3124

3125
        @SuppressWarnings("unchecked")
3126
        public Chain<T> intersection(final List<T>... lists) {
3127
            return new Chain<>(Underscore.intersection(list, lists));
1✔
3128
        }
3129

3130
        @SuppressWarnings("unchecked")
3131
        public Chain<T> difference(final List<T>... lists) {
3132
            return new Chain<>(Underscore.difference(list, lists));
1✔
3133
        }
3134

3135
        public Chain<Integer> range(final int stop) {
3136
            return new Chain<>(Underscore.range(stop));
1✔
3137
        }
3138

3139
        public Chain<Integer> range(final int start, final int stop) {
3140
            return new Chain<>(Underscore.range(start, stop));
1✔
3141
        }
3142

3143
        public Chain<Integer> range(final int start, final int stop, final int step) {
3144
            return new Chain<>(Underscore.range(start, stop, step));
1✔
3145
        }
3146

3147
        public Chain<List<T>> chunk(final int size) {
3148
            return new Chain<>(Underscore.chunk(value(), size, size));
1✔
3149
        }
3150

3151
        public Chain<List<T>> chunk(final int size, final int step) {
3152
            return new Chain<>(Underscore.chunk(value(), size, step));
1✔
3153
        }
3154

3155
        public Chain<List<T>> chunkFill(final int size, final T fillValue) {
3156
            return new Chain<>(Underscore.chunkFill(value(), size, size, fillValue));
1✔
3157
        }
3158

3159
        public Chain<List<T>> chunkFill(final int size, final int step, final T fillValue) {
3160
            return new Chain<>(Underscore.chunkFill(value(), size, step, fillValue));
1✔
3161
        }
3162

3163
        public Chain<T> cycle(final int times) {
3164
            return new Chain<>(Underscore.cycle(value(), times));
1✔
3165
        }
3166

3167
        public Chain<T> interpose(final T element) {
3168
            return new Chain<>(Underscore.interpose(value(), element));
1✔
3169
        }
3170

3171
        public Chain<T> interposeByList(final Iterable<T> interIter) {
3172
            return new Chain<>(Underscore.interposeByList(value(), interIter));
1✔
3173
        }
3174

3175
        @SuppressWarnings("unchecked")
3176
        public Chain<T> concat(final List<T>... lists) {
3177
            return new Chain<>(Underscore.concat(list, lists));
1✔
3178
        }
3179

3180
        public Chain<T> slice(final int start) {
3181
            return new Chain<>(Underscore.slice(list, start));
1✔
3182
        }
3183

3184
        public Chain<T> slice(final int start, final int end) {
3185
            return new Chain<>(Underscore.slice(list, start, end));
1✔
3186
        }
3187

3188
        public Chain<List<T>> splitAt(final int position) {
3189
            return new Chain<>(Underscore.splitAt(list, position));
1✔
3190
        }
3191

3192
        public Chain<T> takeSkipping(final int stepSize) {
3193
            return new Chain<>(Underscore.takeSkipping(list, stepSize));
1✔
3194
        }
3195

3196
        public Chain<T> reverse() {
3197
            return new Chain<>(Underscore.reverse(list));
1✔
3198
        }
3199

3200
        public Chain<String> join() {
3201
            return new Chain<>(Underscore.join(list));
1✔
3202
        }
3203

3204
        public Chain<String> join(final String separator) {
3205
            return new Chain<>(Underscore.join(list, separator));
1✔
3206
        }
3207

3208
        @SuppressWarnings("unchecked")
3209
        public Chain<T> push(final T... values) {
3210
            return new Chain<>(Underscore.push(value(), values));
1✔
3211
        }
3212

3213
        public Chain<Map.Entry<T, List<T>>> pop() {
3214
            return new Chain<>(Underscore.pop(value()));
1✔
3215
        }
3216

3217
        public Chain<Map.Entry<T, List<T>>> shift() {
3218
            return new Chain<>(Underscore.shift(value()));
1✔
3219
        }
3220

3221
        @SuppressWarnings("unchecked")
3222
        public Chain<T> unshift(final T... values) {
3223
            return new Chain<>(Underscore.unshift(value(), values));
1✔
3224
        }
3225

3226
        public Chain<T> skip(final int numberToSkip) {
3227
            return new Chain<>(list.subList(numberToSkip, list.size()));
1✔
3228
        }
3229

3230
        public Chain<T> limit(final int size) {
3231
            return new Chain<>(Underscore.first(list, size));
1✔
3232
        }
3233

3234
        @SuppressWarnings("unchecked")
3235
        public <K, V> Chain<Map<K, V>> toMap() {
3236
            return new Chain<>(Underscore.toMap((Iterable<Map.Entry<K, V>>) list));
1✔
3237
        }
3238

3239
        public boolean isEmpty() {
3240
            return Underscore.isEmpty(list);
1✔
3241
        }
3242

3243
        public boolean isNotEmpty() {
3244
            return Underscore.isNotEmpty(list);
1✔
3245
        }
3246

3247
        public int size() {
3248
            return Underscore.size(list);
1✔
3249
        }
3250

3251
        public T item() {
3252
            return item;
1✔
3253
        }
3254

3255
        /*
3256
         * Documented, #value
3257
         */
3258
        public List<T> value() {
3259
            return list;
1✔
3260
        }
3261

3262
        public Map<String, Object> map() {
3263
            return map;
1✔
3264
        }
3265

3266
        public List<T> toList() {
3267
            return list;
1✔
3268
        }
3269

3270
        public String toString() {
3271
            return String.valueOf(list);
1✔
3272
        }
3273
    }
3274

3275
    /*
3276
     * Documented, #mixin
3277
     */
3278
    public static void mixin(final String funcName, final UnaryOperator<String> func) {
3279
        FUNCTIONS.put(funcName, func);
1✔
3280
    }
1✔
3281

3282
    public Optional<String> call(final String funcName) {
3283
        if (string.isPresent() && FUNCTIONS.containsKey(funcName)) {
1✔
3284
            return Optional.of(FUNCTIONS.get(funcName).apply(string.get()));
1✔
3285
        }
3286
        return Optional.empty();
1✔
3287
    }
3288

3289
    public static <T extends Comparable<T>> List<T> sort(final Iterable<T> iterable) {
3290
        final List<T> localList = newArrayList(iterable);
1✔
3291
        Collections.sort(localList);
1✔
3292
        return localList;
1✔
3293
    }
3294

3295
    @SuppressWarnings("unchecked")
3296
    public static <T extends Comparable<T>> T[] sort(final T... array) {
3297
        final T[] localArray = array.clone();
1✔
3298
        Arrays.sort(localArray);
1✔
3299
        return localArray;
1✔
3300
    }
3301

3302
    @SuppressWarnings("unchecked")
3303
    public List<Comparable> sort() {
3304
        return sort((Iterable<Comparable>) iterable);
1✔
3305
    }
3306

3307
    /*
3308
     * Documented, #join
3309
     */
3310
    public static <T> String join(final Iterable<T> iterable, final String separator) {
3311
        final StringBuilder sb = new StringBuilder();
1✔
3312
        int index = 0;
1✔
3313
        for (final T item : iterable) {
1✔
3314
            if (index > 0) {
1✔
3315
                sb.append(separator);
1✔
3316
            }
3317
            sb.append(item.toString());
1✔
3318
            index += 1;
1✔
3319
        }
1✔
3320
        return sb.toString();
1✔
3321
    }
3322

3323
    public static <T> String join(final Iterable<T> iterable) {
3324
        return join(iterable, " ");
1✔
3325
    }
3326

3327
    public static <T> String join(final T[] array, final String separator) {
3328
        return join(Arrays.asList(array), separator);
1✔
3329
    }
3330

3331
    public static <T> String join(final T[] array) {
3332
        return join(array, " ");
1✔
3333
    }
3334

3335
    public String join(final String separator) {
3336
        return join(iterable, separator);
1✔
3337
    }
3338

3339
    public String join() {
3340
        return join(iterable);
1✔
3341
    }
3342

3343
    @SuppressWarnings("unchecked")
3344
    public static <T> List<T> push(final List<T> list, final T... values) {
3345
        final List<T> result = newArrayList(list);
1✔
3346
        Collections.addAll(result, values);
1✔
3347
        return result;
1✔
3348
    }
3349

3350
    @SuppressWarnings("unchecked")
3351
    public List<T> push(final T... values) {
3352
        return push((List<T>) getIterable(), values);
1✔
3353
    }
3354

3355
    public static <T> Map.Entry<T, List<T>> pop(final List<T> list) {
3356
        return Map.entry(last(list), initial(list));
1✔
3357
    }
3358

3359
    public Map.Entry<T, List<T>> pop() {
3360
        return pop((List<T>) getIterable());
1✔
3361
    }
3362

3363
    @SuppressWarnings("unchecked")
3364
    public static <T> List<T> unshift(final List<T> list, final T... values) {
3365
        final List<T> result = newArrayList(list);
1✔
3366
        int index = 0;
1✔
3367
        for (T value : values) {
1✔
3368
            result.add(index, value);
1✔
3369
            index += 1;
1✔
3370
        }
3371
        return result;
1✔
3372
    }
3373

3374
    @SuppressWarnings("unchecked")
3375
    public List<T> unshift(final T... values) {
3376
        return unshift((List<T>) getIterable(), values);
1✔
3377
    }
3378

3379
    public static <T> Map.Entry<T, List<T>> shift(final List<T> list) {
3380
        return Map.entry(first(list), rest(list));
1✔
3381
    }
3382

3383
    public Map.Entry<T, List<T>> shift() {
3384
        return shift((List<T>) getIterable());
1✔
3385
    }
3386

3387
    @SuppressWarnings("unchecked")
3388
    public static <T> T[] concat(final T[] first, final T[]... other) {
3389
        int length = 0;
1✔
3390
        for (T[] otherItem : other) {
1✔
3391
            length += otherItem.length;
1✔
3392
        }
3393
        final T[] result = Arrays.copyOf(first, first.length + length);
1✔
3394
        int index = 0;
1✔
3395
        for (T[] otherItem : other) {
1✔
3396
            System.arraycopy(otherItem, 0, result, first.length + index, otherItem.length);
1✔
3397
            index += otherItem.length;
1✔
3398
        }
3399
        return result;
1✔
3400
    }
3401

3402
    /*
3403
     * Documented, #concat
3404
     */
3405
    @SuppressWarnings("unchecked")
3406
    public static <T> List<T> concat(final Iterable<T> first, final Iterable<T>... other) {
3407
        List<T> list = newArrayList(first);
1✔
3408
        for (Iterable<T> iter : other) {
1✔
3409
            list.addAll(newArrayList(iter));
1✔
3410
        }
3411
        return list;
1✔
3412
    }
3413

3414
    @SuppressWarnings("unchecked")
3415
    public List<T> concatWith(final Iterable<T>... other) {
3416
        return concat(iterable, other);
1✔
3417
    }
3418

3419
    /*
3420
     * Documented, #slice
3421
     */
3422
    public static <T> List<T> slice(final Iterable<T> iterable, final int start) {
3423
        final List<T> result;
3424
        if (start >= 0) {
1✔
3425
            result = newArrayList(iterable).subList(start, size(iterable));
1✔
3426
        } else {
3427
            result = newArrayList(iterable).subList(size(iterable) + start, size(iterable));
1✔
3428
        }
3429
        return result;
1✔
3430
    }
3431

3432
    public static <T> T[] slice(final T[] array, final int start) {
3433
        final T[] result;
3434
        if (start >= 0) {
1✔
3435
            result = Arrays.copyOfRange(array, start, array.length);
1✔
3436
        } else {
3437
            result = Arrays.copyOfRange(array, array.length + start, array.length);
1✔
3438
        }
3439
        return result;
1✔
3440
    }
3441

3442
    public List<T> slice(final int start) {
3443
        return slice(iterable, start);
1✔
3444
    }
3445

3446
    public static <T> List<T> slice(final Iterable<T> iterable, final int start, final int end) {
3447
        final List<T> result;
3448
        if (start >= 0) {
1✔
3449
            if (end > 0) {
1✔
3450
                result = newArrayList(iterable).subList(start, end);
1✔
3451
            } else {
3452
                result = newArrayList(iterable).subList(start, size(iterable) + end);
1✔
3453
            }
3454
        } else {
3455
            if (end > 0) {
1✔
3456
                result = newArrayList(iterable).subList(size(iterable) + start, end);
1✔
3457
            } else {
3458
                result =
1✔
3459
                        newArrayList(iterable)
1✔
3460
                                .subList(size(iterable) + start, size(iterable) + end);
1✔
3461
            }
3462
        }
3463
        return result;
1✔
3464
    }
3465

3466
    public static <T> T[] slice(final T[] array, final int start, final int end) {
3467
        final T[] result;
3468
        if (start >= 0) {
1✔
3469
            if (end > 0) {
1✔
3470
                result = Arrays.copyOfRange(array, start, end);
1✔
3471
            } else {
3472
                result = Arrays.copyOfRange(array, start, array.length + end);
1✔
3473
            }
3474
        } else {
3475
            if (end > 0) {
1✔
3476
                result = Arrays.copyOfRange(array, array.length + start, end);
1✔
3477
            } else {
3478
                result = Arrays.copyOfRange(array, array.length + start, array.length + end);
1✔
3479
            }
3480
        }
3481
        return result;
1✔
3482
    }
3483

3484
    public List<T> slice(final int start, final int end) {
3485
        return slice(iterable, start, end);
1✔
3486
    }
3487

3488
    public static <T> List<List<T>> splitAt(final Iterable<T> iterable, final int position) {
3489
        List<List<T>> result = new ArrayList<>();
1✔
3490
        int size = size(iterable);
1✔
3491
        final int index;
3492
        if (position < 0) {
1✔
3493
            index = 0;
1✔
3494
        } else {
3495
            index = position > size ? size : position;
1✔
3496
        }
3497
        result.add(newArrayList(iterable).subList(0, index));
1✔
3498
        result.add(newArrayList(iterable).subList(index, size));
1✔
3499
        return result;
1✔
3500
    }
3501

3502
    public static <T> List<List<T>> splitAt(final T[] array, final int position) {
3503
        return splitAt(Arrays.asList(array), position);
1✔
3504
    }
3505

3506
    public List<List<T>> splitAt(final int position) {
3507
        return splitAt(iterable, position);
1✔
3508
    }
3509

3510
    public static <T> List<T> takeSkipping(final Iterable<T> iterable, final int stepSize) {
3511
        List<T> result = new ArrayList<>();
1✔
3512
        if (stepSize <= 0) {
1✔
3513
            return result;
1✔
3514
        }
3515
        int size = size(iterable);
1✔
3516
        if (stepSize > size) {
1✔
3517
            result.add(first(iterable));
1✔
3518
            return result;
1✔
3519
        }
3520
        int i = 0;
1✔
3521
        for (T element : iterable) {
1✔
3522
            if (i++ % stepSize == 0) {
1✔
3523
                result.add(element);
1✔
3524
            }
3525
        }
1✔
3526
        return result;
1✔
3527
    }
3528

3529
    public static <T> List<T> takeSkipping(final T[] array, final int stepSize) {
3530
        return takeSkipping(Arrays.asList(array), stepSize);
1✔
3531
    }
3532

3533
    public List<T> takeSkipping(final int stepSize) {
3534
        return takeSkipping(iterable, stepSize);
1✔
3535
    }
3536

3537
    /*
3538
     * Documented, #reverse
3539
     */
3540
    public static <T> List<T> reverse(final Iterable<T> iterable) {
3541
        final List<T> result = newArrayList(iterable);
1✔
3542
        Collections.reverse(result);
1✔
3543
        return result;
1✔
3544
    }
3545

3546
    @SuppressWarnings("unchecked")
3547
    public static <T> T[] reverse(final T... array) {
3548
        T temp;
3549
        final T[] newArray = array.clone();
1✔
3550
        for (int index = 0; index < array.length / 2; index += 1) {
1✔
3551
            temp = newArray[index];
1✔
3552
            newArray[index] = newArray[array.length - 1 - index];
1✔
3553
            newArray[array.length - 1 - index] = temp;
1✔
3554
        }
3555
        return newArray;
1✔
3556
    }
3557

3558
    public static List<Integer> reverse(final int[] array) {
3559
        final List<Integer> result = newIntegerList(array);
1✔
3560
        Collections.reverse(result);
1✔
3561
        return result;
1✔
3562
    }
3563

3564
    public List<T> reverse() {
3565
        return reverse(iterable);
1✔
3566
    }
3567

3568
    public Iterable<T> getIterable() {
3569
        return iterable;
1✔
3570
    }
3571

3572
    public Iterable<T> value() {
3573
        return iterable;
1✔
3574
    }
3575

3576
    public Optional<String> getString() {
3577
        return string;
1✔
3578
    }
3579

3580
    public static <T> java.util.concurrent.ScheduledFuture<T> setTimeout(
3581
            final Supplier<T> function, final int delayMilliseconds) {
3582
        return delay(function, delayMilliseconds);
1✔
3583
    }
3584

3585
    public static void clearTimeout(java.util.concurrent.ScheduledFuture<?> scheduledFuture) {
3586
        if (scheduledFuture != null) {
1✔
3587
            scheduledFuture.cancel(true);
1✔
3588
        }
3589
    }
1✔
3590

3591
    public static <T> java.util.concurrent.ScheduledFuture setInterval(
3592
            final Supplier<T> function, final int delayMilliseconds) {
3593
        final java.util.concurrent.ScheduledExecutorService scheduler =
3594
                java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
1✔
3595
        return scheduler.scheduleAtFixedRate(
1✔
3596
                function::get,
1✔
3597
                delayMilliseconds,
3598
                delayMilliseconds,
3599
                java.util.concurrent.TimeUnit.MILLISECONDS);
3600
    }
3601

3602
    public static void clearInterval(java.util.concurrent.ScheduledFuture scheduledFuture) {
3603
        clearTimeout(scheduledFuture);
1✔
3604
    }
1✔
3605

3606
    public static <T> List<T> copyOf(final Iterable<T> iterable) {
3607
        return newArrayList(iterable);
1✔
3608
    }
3609

3610
    public List<T> copyOf() {
3611
        return newArrayList(value());
1✔
3612
    }
3613

3614
    public static <T> List<T> copyOfRange(
3615
            final Iterable<T> iterable, final int start, final int end) {
3616
        return slice(iterable, start, end);
1✔
3617
    }
3618

3619
    public List<T> copyOfRange(final int start, final int end) {
3620
        return slice(value(), start, end);
1✔
3621
    }
3622

3623
    public static <T> T elementAt(final List<T> list, final int index) {
3624
        return list.get(index);
1✔
3625
    }
3626

3627
    public T elementAt(final int index) {
3628
        return elementAt((List<T>) value(), index);
1✔
3629
    }
3630

3631
    public static <T> T get(final List<T> list, final int index) {
3632
        return elementAt(list, index);
1✔
3633
    }
3634

3635
    public T get(final int index) {
3636
        return elementAt((List<T>) value(), index);
1✔
3637
    }
3638

3639
    public static <T> Map.Entry<T, List<T>> set(
3640
            final List<T> list, final int index, final T value) {
3641
        final List<T> newList = newArrayList(list);
1✔
3642
        return Map.entry(newList.set(index, value), newList);
1✔
3643
    }
3644

3645
    public Map.Entry<T, List<T>> set(final int index, final T value) {
3646
        return set((List<T>) value(), index, value);
1✔
3647
    }
3648

3649
    public static <T> T elementAtOrElse(final List<T> list, final int index, T defaultValue) {
3650
        try {
3651
            return list.get(index);
1✔
3652
        } catch (IndexOutOfBoundsException ex) {
1✔
3653
            return defaultValue;
1✔
3654
        }
3655
    }
3656

3657
    public T elementAtOrElse(final int index, T defaultValue) {
3658
        return elementAtOrElse((List<T>) value(), index, defaultValue);
1✔
3659
    }
3660

3661
    public static <T> T elementAtOrNull(final List<T> list, final int index) {
3662
        try {
3663
            return list.get(index);
1✔
3664
        } catch (IndexOutOfBoundsException ex) {
1✔
3665
            return null;
1✔
3666
        }
3667
    }
3668

3669
    public T elementAtOrNull(final int index) {
3670
        return elementAtOrNull((List<T>) value(), index);
1✔
3671
    }
3672

3673
    public static <T> int lastIndex(final Iterable<T> iterable) {
3674
        return size(iterable) - 1;
1✔
3675
    }
3676

3677
    public static <T> int lastIndex(final T[] array) {
3678
        return array.length - 1;
1✔
3679
    }
3680

3681
    public static int lastIndex(final int[] array) {
3682
        return array.length - 1;
1✔
3683
    }
3684

3685
    public static <T> T checkNotNull(T reference) {
3686
        if (reference == null) {
1✔
3687
            throw new NullPointerException();
1✔
3688
        }
3689
        return reference;
1✔
3690
    }
3691

3692
    public static <T> List<T> checkNotNullElements(List<T> references) {
3693
        if (references == null) {
1✔
3694
            throw new NullPointerException();
1✔
3695
        }
3696
        for (T reference : references) {
1✔
3697
            checkNotNull(reference);
1✔
3698
        }
1✔
3699
        return references;
1✔
3700
    }
3701

3702
    public static <T> T checkNotNull(T reference, Object errorMessage) {
3703
        if (reference == null) {
1✔
3704
            throw new NullPointerException(String.valueOf(errorMessage));
1✔
3705
        }
3706
        return reference;
1✔
3707
    }
3708

3709
    public static boolean nonNull(Object obj) {
3710
        return obj != null;
1✔
3711
    }
3712

3713
    public static <T> T defaultTo(T value, T defaultValue) {
3714
        if (value == null) {
1✔
3715
            return defaultValue;
1✔
3716
        }
3717
        return value;
1✔
3718
    }
3719

3720
    protected static <T> List<T> newArrayList(final Iterable<T> iterable) {
3721
        final List<T> result;
3722
        if (iterable instanceof Collection) {
1✔
3723
            result = new ArrayList<>((Collection<T>) iterable);
1✔
3724
        } else {
3725
            result = new ArrayList<>();
1✔
3726
            for (final T item : iterable) {
1✔
3727
                result.add(item);
1✔
3728
            }
1✔
3729
        }
3730
        return result;
1✔
3731
    }
3732

3733
    protected static <T> List<T> newArrayList(final T object) {
3734
        final List<T> result = new ArrayList<>();
1✔
3735
        result.add(object);
1✔
3736
        return result;
1✔
3737
    }
3738

3739
    protected static <T> List<T> newArrayList(final Iterable<T> iterable, final int size) {
3740
        final List<T> result = new ArrayList<>();
1✔
3741
        for (int index = 0; iterable.iterator().hasNext() && index < size; index += 1) {
1✔
3742
            result.add(iterable.iterator().next());
1✔
3743
        }
3744
        return result;
1✔
3745
    }
3746

3747
    protected static List<Integer> newIntegerList(int... array) {
3748
        final List<Integer> result = new ArrayList<>(array.length);
1✔
3749
        for (final int item : array) {
1✔
3750
            result.add(item);
1✔
3751
        }
3752
        return result;
1✔
3753
    }
3754

3755
    protected static <T> List<T> newArrayListWithExpectedSize(int size) {
3756
        return new ArrayList<>((int) (CAPACITY_SIZE_5 + size + (size / 10)));
1✔
3757
    }
3758

3759
    protected static <T> Set<T> newLinkedHashSet(Iterable<T> iterable) {
3760
        final Set<T> result = new LinkedHashSet<>();
1✔
3761
        for (final T item : iterable) {
1✔
3762
            result.add(item);
1✔
3763
        }
1✔
3764
        return result;
1✔
3765
    }
3766

3767
    protected static <T> Set<T> newLinkedHashSetWithExpectedSize(int size) {
3768
        return new LinkedHashSet<>((int) Math.max(size * CAPACITY_COEFF_2, CAPACITY_SIZE_16));
1✔
3769
    }
3770

3771
    @SuppressWarnings("unchecked")
3772
    public static <T> Predicate<T> and(
3773
            final Predicate<? super T> pred1,
3774
            final Predicate<? super T> pred2,
3775
            final Predicate<? super T>... rest) {
3776
        checkNotNull(pred1);
1✔
3777
        checkNotNull(pred2);
1✔
3778
        checkNotNullElements(Arrays.asList(rest));
1✔
3779
        return value -> {
1✔
3780
            boolean result = pred1.test(value) && pred2.test(value);
1✔
3781
            if (!result) {
1✔
3782
                return false;
1✔
3783
            }
3784
            for (Predicate<? super T> predicate : rest) {
1✔
3785
                if (!predicate.test(value)) {
1✔
3786
                    return false;
1✔
3787
                }
3788
            }
3789
            return true;
1✔
3790
        };
3791
    }
3792

3793
    @SuppressWarnings("unchecked")
3794
    public static <T> Predicate<T> or(
3795
            final Predicate<? super T> pred1,
3796
            final Predicate<? super T> pred2,
3797
            final Predicate<? super T>... rest) {
3798
        checkNotNull(pred1);
1✔
3799
        checkNotNull(pred2);
1✔
3800
        checkNotNullElements(Arrays.asList(rest));
1✔
3801
        return value -> {
1✔
3802
            boolean result = pred1.test(value) || pred2.test(value);
1✔
3803
            if (result) {
1✔
3804
                return true;
1✔
3805
            }
3806
            for (Predicate<? super T> predicate : rest) {
1✔
3807
                if (predicate.test(value)) {
1✔
3808
                    return true;
1✔
3809
                }
3810
            }
3811
            return false;
1✔
3812
        };
3813
    }
3814

3815
    public static void main(String... args) {
3816
        final String message =
1✔
3817
                "Underscore-java is a java port of Underscore.js.\n\n"
3818
                        + "In addition to porting Underscore's functionality,"
3819
                        + " Underscore-java includes matching unit tests.\n\n"
3820
                        + "For docs, license, tests, and downloads, see: https://javadev.github.io/underscore-java";
3821
        System.out.println(message);
1✔
3822
    }
1✔
3823

3824
    public static interface Function3<F1, F2, F3, T> {
3825
        T apply(F1 arg1, F2 arg2, F3 arg3);
3826
    }
3827

3828
    public abstract static class MemoizeFunction<F, T> implements Function<F, T> {
1✔
3829
        private final Map<F, T> cache = new LinkedHashMap<>();
1✔
3830

3831
        public abstract T calc(final F n);
3832

3833
        public T apply(final F key) {
3834
            cache.putIfAbsent(key, calc(key));
1✔
3835
            return cache.get(key);
1✔
3836
        }
3837
    }
3838

3839
    public static interface PredicateIndexed<T> {
3840
        boolean test(int index, T arg);
3841
    }
3842

3843
    public static interface Template<T> extends Function<T, String> {
3844
        List<String> check(T arg);
3845
    }
3846
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc