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

javadev / underscore-java / #3312

01 Sep 2023 02:17PM UTC coverage: 99.954% (-0.05%) from 100.0%
#3312

push

web-flow
Merge 1a6acd990 into 5712be1d4

4329 of 4331 relevant lines covered (99.95%)

1.0 hits per line

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

99.86
/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 = newLinkedHashMap();
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 = newArrayList();
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 = newArrayList();
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 = newArrayList();
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 = newArrayList();
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 = newLinkedHashSet();
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 = newArrayList();
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 = newLinkedHashMap();
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 = newArrayList();
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 = newLinkedHashMap();
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
    @SuppressWarnings("unchecked")
1050
    public static <K, E> Map<K, List<E>> indexBy(
1051
            final Iterable<E> iterable, final String property) {
1052
        return groupBy(
1✔
1053
                iterable,
1054
                elem -> {
1055
                    try {
1056
                        return (K) elem.getClass().getField(property).get(elem);
1✔
1057
                    } catch (Exception e) {
1✔
1058
                        return null;
1✔
1059
                    }
1060
                });
1061
    }
1062

1063
    @SuppressWarnings("unchecked")
1064
    public <K, E> Map<K, List<E>> indexBy(final String property) {
1065
        return indexBy((Iterable<E>) iterable, property);
1✔
1066
    }
1067

1068
    /*
1069
     * Documented, #countBy
1070
     */
1071
    public static <K, E> Map<K, Integer> countBy(final Iterable<E> iterable, Function<E, K> func) {
1072
        final Map<K, Integer> retVal = newLinkedHashMap();
1✔
1073
        for (E e : iterable) {
1✔
1074
            final K key = func.apply(e);
1✔
1075
            if (retVal.containsKey(key)) {
1✔
1076
                retVal.put(key, 1 + retVal.get(key));
1✔
1077
            } else {
1078
                retVal.put(key, 1);
1✔
1079
            }
1080
        }
1✔
1081
        return retVal;
1✔
1082
    }
1083

1084
    public static <K> Map<K, Integer> countBy(final Iterable<K> iterable) {
1085
        final Map<K, Integer> retVal = newLinkedHashMap();
1✔
1086
        for (K key : iterable) {
1✔
1087
            if (retVal.containsKey(key)) {
1✔
1088
                retVal.put(key, 1 + retVal.get(key));
1✔
1089
            } else {
1090
                retVal.put(key, 1);
1✔
1091
            }
1092
        }
1✔
1093
        return retVal;
1✔
1094
    }
1095

1096
    @SuppressWarnings("unchecked")
1097
    public <K, E> Map<K, Integer> countBy(Function<E, K> func) {
1098
        return countBy((Iterable<E>) iterable, func);
1✔
1099
    }
1100

1101
    @SuppressWarnings("unchecked")
1102
    public <K> Map<K, Integer> countBy() {
1103
        return countBy((Iterable<K>) iterable);
1✔
1104
    }
1105

1106
    /*
1107
     * Documented, #toArray
1108
     */
1109
    @SuppressWarnings("unchecked")
1110
    public static <E> E[] toArray(final Iterable<E> iterable) {
1111
        return (E[]) newArrayList(iterable).toArray();
1✔
1112
    }
1113

1114
    @SuppressWarnings("unchecked")
1115
    public <E> E[] toArray() {
1116
        return toArray((Iterable<E>) iterable);
1✔
1117
    }
1118

1119
    /*
1120
     * Documented, #toMap
1121
     */
1122
    public static <K, V> Map<K, V> toMap(final Iterable<Map.Entry<K, V>> iterable) {
1123
        final Map<K, V> result = newLinkedHashMap();
1✔
1124
        for (Map.Entry<K, V> entry : iterable) {
1✔
1125
            result.put(entry.getKey(), entry.getValue());
1✔
1126
        }
1✔
1127
        return result;
1✔
1128
    }
1129

1130
    @SuppressWarnings("unchecked")
1131
    public <K, V> Map<K, V> toMap() {
1132
        return toMap((Iterable<Map.Entry<K, V>>) iterable);
1✔
1133
    }
1134

1135
    public static <K, V> Map<K, V> toMap(final List<Map.Entry<K, V>> tuples) {
1136
        final Map<K, V> result = newLinkedHashMap();
1✔
1137
        for (final Map.Entry<K, V> entry : tuples) {
1✔
1138
            result.put(entry.getKey(), entry.getValue());
1✔
1139
        }
1✔
1140
        return result;
1✔
1141
    }
1142

1143
    public Map<T, Integer> toCardinalityMap() {
1144
        return toCardinalityMap(iterable);
1✔
1145
    }
1146

1147
    public static <K> Map<K, Integer> toCardinalityMap(final Iterable<K> iterable) {
1148
        Iterator<K> iterator = iterable.iterator();
1✔
1149
        Map<K, Integer> result = newLinkedHashMap();
1✔
1150

1151
        while (iterator.hasNext()) {
1✔
1152
            K item = iterator.next();
1✔
1153

1154
            if (result.containsKey(item)) {
1✔
1155
                result.put(item, result.get(item) + 1);
1✔
1156
            } else {
1157
                result.put(item, 1);
1✔
1158
            }
1159
        }
1✔
1160
        return result;
1✔
1161
    }
1162

1163
    /*
1164
     * Documented, #size
1165
     */
1166
    public static int size(final Iterable<?> iterable) {
1167
        if (iterable instanceof Collection) {
1✔
1168
            return ((Collection) iterable).size();
1✔
1169
        }
1170
        int size;
1171
        final Iterator<?> iterator = iterable.iterator();
1✔
1172
        for (size = 0; iterator.hasNext(); size += 1) {
1✔
1173
            iterator.next();
1✔
1174
        }
1175
        return size;
1✔
1176
    }
1177

1178
    public int size() {
1179
        return size(iterable);
1✔
1180
    }
1181

1182
    @SuppressWarnings("unchecked")
1183
    public static <E> int size(final E... array) {
1184
        return array.length;
1✔
1185
    }
1186

1187
    public static <E> List<List<E>> partition(final Iterable<E> iterable, final Predicate<E> pred) {
1188
        final List<E> retVal1 = newArrayList();
1✔
1189
        final List<E> retVal2 = newArrayList();
1✔
1190
        for (final E e : iterable) {
1✔
1191
            if (pred.test(e)) {
1✔
1192
                retVal1.add(e);
1✔
1193
            } else {
1194
                retVal2.add(e);
1✔
1195
            }
1196
        }
1✔
1197
        return Arrays.asList(retVal1, retVal2);
1✔
1198
    }
1199

1200
    @SuppressWarnings("unchecked")
1201
    public static <E> List<E>[] partition(final E[] iterable, final Predicate<E> pred) {
1202
        return partition(Arrays.asList(iterable), pred).toArray(new ArrayList[0]);
1✔
1203
    }
1204

1205
    public T singleOrNull() {
1206
        return singleOrNull(iterable);
1✔
1207
    }
1208

1209
    public T singleOrNull(Predicate<T> pred) {
1210
        return singleOrNull(iterable, pred);
1✔
1211
    }
1212

1213
    public static <E> E singleOrNull(final Iterable<E> iterable) {
1214
        Iterator<E> iterator = iterable.iterator();
1✔
1215
        if (!iterator.hasNext()) {
1✔
1216
            return null;
1✔
1217
        }
1218
        E result = iterator.next();
1✔
1219

1220
        if (iterator.hasNext()) {
1✔
1221
            result = null;
1✔
1222
        }
1223
        return result;
1✔
1224
    }
1225

1226
    public static <E> E singleOrNull(final Iterable<E> iterable, Predicate<E> pred) {
1227
        return singleOrNull(filter(iterable, pred));
1✔
1228
    }
1229

1230
    /*
1231
     * Documented, #first
1232
     */
1233
    public static <E> E first(final Iterable<E> iterable) {
1234
        return iterable.iterator().next();
1✔
1235
    }
1236

1237
    @SuppressWarnings("unchecked")
1238
    public static <E> E first(final E... array) {
1239
        return array[0];
1✔
1240
    }
1241

1242
    public static <E> List<E> first(final List<E> list, final int n) {
1243
        return list.subList(0, Math.min(n < 0 ? 0 : n, list.size()));
1✔
1244
    }
1245

1246
    public T first() {
1247
        return first(iterable);
1✔
1248
    }
1249

1250
    public List<T> first(final int n) {
1251
        return first(newArrayList(iterable), n);
1✔
1252
    }
1253

1254
    public static <E> E first(final Iterable<E> iterable, final Predicate<E> pred) {
1255
        return filter(newArrayList(iterable), pred).iterator().next();
1✔
1256
    }
1257

1258
    public static <E> List<E> first(
1259
            final Iterable<E> iterable, final Predicate<E> pred, final int n) {
1260
        List<E> list = filter(newArrayList(iterable), pred);
1✔
1261
        return list.subList(0, Math.min(n < 0 ? 0 : n, list.size()));
1✔
1262
    }
1263

1264
    public T first(final Predicate<T> pred) {
1265
        return first(newArrayList(iterable), pred);
1✔
1266
    }
1267

1268
    public List<T> first(final Predicate<T> pred, final int n) {
1269
        return first(newArrayList(iterable), pred, n);
1✔
1270
    }
1271

1272
    public static <E> E firstOrNull(final Iterable<E> iterable) {
1273
        final Iterator<E> iterator = iterable.iterator();
1✔
1274
        return iterator.hasNext() ? iterator.next() : null;
1✔
1275
    }
1276

1277
    public T firstOrNull() {
1278
        return firstOrNull(iterable);
1✔
1279
    }
1280

1281
    public static <E> E firstOrNull(final Iterable<E> iterable, final Predicate<E> pred) {
1282
        final Iterator<E> iterator = filter(newArrayList(iterable), pred).iterator();
1✔
1283
        return iterator.hasNext() ? iterator.next() : null;
1✔
1284
    }
1285

1286
    public T firstOrNull(final Predicate<T> pred) {
1287
        return firstOrNull(iterable, pred);
1✔
1288
    }
1289

1290
    public static <E> E head(final Iterable<E> iterable) {
1291
        return first(iterable);
1✔
1292
    }
1293

1294
    @SuppressWarnings("unchecked")
1295
    public static <E> E head(final E... array) {
1296
        return first(array);
1✔
1297
    }
1298

1299
    public static <E> List<E> head(final List<E> list, final int n) {
1300
        return first(list, n);
1✔
1301
    }
1302

1303
    public T head() {
1304
        return first();
1✔
1305
    }
1306

1307
    public List<T> head(final int n) {
1308
        return first(n);
1✔
1309
    }
1310

1311
    /*
1312
     * Documented, #initial
1313
     */
1314
    public static <E> List<E> initial(final List<E> list) {
1315
        return initial(list, 1);
1✔
1316
    }
1317

1318
    public static <E> List<E> initial(final List<E> list, final int n) {
1319
        return list.subList(0, Math.max(0, list.size() - n));
1✔
1320
    }
1321

1322
    @SuppressWarnings("unchecked")
1323
    public static <E> E[] initial(final E... array) {
1324
        return initial(array, 1);
1✔
1325
    }
1326

1327
    public static <E> E[] initial(final E[] array, final int n) {
1328
        return Arrays.copyOf(array, array.length - n);
1✔
1329
    }
1330

1331
    public List<T> initial() {
1332
        return initial((List<T>) iterable, 1);
1✔
1333
    }
1334

1335
    public List<T> initial(final int n) {
1336
        return initial((List<T>) iterable, n);
1✔
1337
    }
1338

1339
    @SuppressWarnings("unchecked")
1340
    public static <E> E last(final E... array) {
1341
        return array[array.length - 1];
1✔
1342
    }
1343

1344
    /*
1345
     * Documented, #last
1346
     */
1347
    public static <E> E last(final List<E> list) {
1348
        return list.get(list.size() - 1);
1✔
1349
    }
1350

1351
    public static <E> List<E> last(final List<E> list, final int n) {
1352
        return list.subList(Math.max(0, list.size() - n), list.size());
1✔
1353
    }
1354

1355
    public T last() {
1356
        return last((List<T>) iterable);
1✔
1357
    }
1358

1359
    public List<T> last(final int n) {
1360
        return last((List<T>) iterable, n);
1✔
1361
    }
1362

1363
    public static <E> E last(final List<E> list, final Predicate<E> pred) {
1364
        final List<E> filteredList = filter(list, pred);
1✔
1365
        return filteredList.get(filteredList.size() - 1);
1✔
1366
    }
1367

1368
    public T last(final Predicate<T> pred) {
1369
        return last((List<T>) iterable, pred);
1✔
1370
    }
1371

1372
    public static <E> E lastOrNull(final List<E> list) {
1373
        return list.isEmpty() ? null : list.get(list.size() - 1);
1✔
1374
    }
1375

1376
    public T lastOrNull() {
1377
        return lastOrNull((List<T>) iterable);
1✔
1378
    }
1379

1380
    public static <E> E lastOrNull(final List<E> list, final Predicate<E> pred) {
1381
        final List<E> filteredList = filter(list, pred);
1✔
1382
        return filteredList.isEmpty() ? null : filteredList.get(filteredList.size() - 1);
1✔
1383
    }
1384

1385
    public T lastOrNull(final Predicate<T> pred) {
1386
        return lastOrNull((List<T>) iterable, pred);
1✔
1387
    }
1388

1389
    /*
1390
     * Documented, #rest
1391
     */
1392
    public static <E> List<E> rest(final List<E> list) {
1393
        return rest(list, 1);
1✔
1394
    }
1395

1396
    public static <E> List<E> rest(final List<E> list, int n) {
1397
        return list.subList(Math.min(n, list.size()), list.size());
1✔
1398
    }
1399

1400
    @SuppressWarnings("unchecked")
1401
    public static <E> E[] rest(final E... array) {
1402
        return rest(array, 1);
1✔
1403
    }
1404

1405
    @SuppressWarnings("unchecked")
1406
    public static <E> E[] rest(final E[] array, final int n) {
1407
        return (E[]) rest(Arrays.asList(array), n).toArray();
1✔
1408
    }
1409

1410
    public List<T> rest() {
1411
        return rest((List<T>) iterable);
1✔
1412
    }
1413

1414
    public List<T> rest(int n) {
1415
        return rest((List<T>) iterable, n);
1✔
1416
    }
1417

1418
    public static <E> List<E> tail(final List<E> list) {
1419
        return rest(list);
1✔
1420
    }
1421

1422
    public static <E> List<E> tail(final List<E> list, final int n) {
1423
        return rest(list, n);
1✔
1424
    }
1425

1426
    @SuppressWarnings("unchecked")
1427
    public static <E> E[] tail(final E... array) {
1428
        return rest(array);
1✔
1429
    }
1430

1431
    public static <E> E[] tail(final E[] array, final int n) {
1432
        return rest(array, n);
1✔
1433
    }
1434

1435
    public List<T> tail() {
1436
        return rest();
1✔
1437
    }
1438

1439
    public List<T> tail(final int n) {
1440
        return rest(n);
1✔
1441
    }
1442

1443
    public static <E> List<E> drop(final List<E> list) {
1444
        return rest(list);
1✔
1445
    }
1446

1447
    public static <E> List<E> drop(final List<E> list, final int n) {
1448
        return rest(list, n);
1✔
1449
    }
1450

1451
    @SuppressWarnings("unchecked")
1452
    public static <E> E[] drop(final E... array) {
1453
        return rest(array);
1✔
1454
    }
1455

1456
    public static <E> E[] drop(final E[] array, final int n) {
1457
        return rest(array, n);
1✔
1458
    }
1459

1460
    /*
1461
     * Documented, #compact
1462
     */
1463
    public static <E> List<E> compact(final List<E> list) {
1464
        return filter(
1✔
1465
                list,
1466
                arg ->
1467
                        !String.valueOf(arg).equals("null")
1✔
1468
                                && !String.valueOf(arg).equals("0")
1✔
1469
                                && !String.valueOf(arg).equals("false")
1✔
1470
                                && !String.valueOf(arg).equals(""));
1✔
1471
    }
1472

1473
    @SuppressWarnings("unchecked")
1474
    public static <E> E[] compact(final E... array) {
1475
        return (E[]) compact(Arrays.asList(array)).toArray();
1✔
1476
    }
1477

1478
    public static <E> List<E> compact(final List<E> list, final E falsyValue) {
1479
        return filter(list, arg -> !(Objects.equals(arg, falsyValue)));
1✔
1480
    }
1481

1482
    @SuppressWarnings("unchecked")
1483
    public static <E> E[] compact(final E[] array, final E falsyValue) {
1484
        return (E[]) compact(Arrays.asList(array), falsyValue).toArray();
1✔
1485
    }
1486

1487
    public List<T> compact() {
1488
        return compact((List<T>) iterable);
1✔
1489
    }
1490

1491
    public List<T> compact(final T falsyValue) {
1492
        return compact((List<T>) iterable, falsyValue);
1✔
1493
    }
1494

1495
    /*
1496
     * Documented, #flatten
1497
     */
1498
    public static <E> List<E> flatten(final List<?> list) {
1499
        List<E> flattened = newArrayList();
1✔
1500
        flatten(list, flattened, -1);
1✔
1501
        return flattened;
1✔
1502
    }
1503

1504
    public static <E> List<E> flatten(final List<?> list, final boolean shallow) {
1505
        List<E> flattened = newArrayList();
1✔
1506
        flatten(list, flattened, shallow ? 1 : -1);
1✔
1507
        return flattened;
1✔
1508
    }
1509

1510
    @SuppressWarnings("unchecked")
1511
    private static <E> void flatten(
1512
            final List<?> fromTreeList, final List<E> toFlatList, final int shallowLevel) {
1513
        for (Object item : fromTreeList) {
1✔
1514
            if (item instanceof List<?> && shallowLevel != 0) {
1✔
1515
                flatten((List<?>) item, toFlatList, shallowLevel - 1);
1✔
1516
            } else {
1517
                toFlatList.add((E) item);
1✔
1518
            }
1519
        }
1✔
1520
    }
1✔
1521

1522
    public List<T> flatten() {
1523
        return flatten((List<T>) iterable);
1✔
1524
    }
1525

1526
    public List<T> flatten(final boolean shallow) {
1527
        return flatten((List<T>) iterable, shallow);
1✔
1528
    }
1529

1530
    /*
1531
     * Documented, #without
1532
     */
1533
    @SuppressWarnings("unchecked")
1534
    public static <E> List<E> without(final List<E> list, E... values) {
1535
        final List<E> valuesList = Arrays.asList(values);
1✔
1536
        return filter(list, elem -> !contains(valuesList, elem));
1✔
1537
    }
1538

1539
    @SuppressWarnings("unchecked")
1540
    public static <E> E[] without(final E[] array, final E... values) {
1541
        return (E[]) without(Arrays.asList(array), values).toArray();
1✔
1542
    }
1543

1544
    /*
1545
     * Documented, #uniq
1546
     */
1547
    public static <E> List<E> uniq(final List<E> list) {
1548
        return newArrayList(newLinkedHashSet(list));
1✔
1549
    }
1550

1551
    @SuppressWarnings("unchecked")
1552
    public static <E> E[] uniq(final E... array) {
1553
        return (E[]) uniq(Arrays.asList(array)).toArray();
1✔
1554
    }
1555

1556
    public static <K, E> Collection<E> uniq(final Iterable<E> iterable, final Function<E, K> func) {
1557
        final Map<K, E> retVal = newLinkedHashMap();
1✔
1558
        for (final E e : iterable) {
1✔
1559
            final K key = func.apply(e);
1✔
1560
            retVal.put(key, e);
1✔
1561
        }
1✔
1562
        return retVal.values();
1✔
1563
    }
1564

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

1570
    public static <E> List<E> distinct(final List<E> list) {
1571
        return uniq(list);
1✔
1572
    }
1573

1574
    @SuppressWarnings("unchecked")
1575
    public static <E> E[] distinct(final E... array) {
1576
        return uniq(array);
1✔
1577
    }
1578

1579
    public static <K, E> Collection<E> distinctBy(
1580
            final Iterable<E> iterable, final Function<E, K> func) {
1581
        return uniq(iterable, func);
1✔
1582
    }
1583

1584
    public static <K, E> E[] distinctBy(final E[] array, final Function<E, K> func) {
1585
        return uniq(array, func);
1✔
1586
    }
1587

1588
    /*
1589
     * Documented, #union
1590
     */
1591
    @SuppressWarnings("unchecked")
1592
    public static <E> List<E> union(final List<E> list, final List<E>... lists) {
1593
        final Set<E> union = newLinkedHashSet();
1✔
1594
        union.addAll(list);
1✔
1595
        for (List<E> localList : lists) {
1✔
1596
            union.addAll(localList);
1✔
1597
        }
1598
        return newArrayList(union);
1✔
1599
    }
1600

1601
    @SuppressWarnings("unchecked")
1602
    public List<T> unionWith(final List<T>... lists) {
1603
        return union(newArrayList(iterable), lists);
1✔
1604
    }
1605

1606
    @SuppressWarnings("unchecked")
1607
    public static <E> E[] union(final E[]... arrays) {
1608
        final Set<E> union = newLinkedHashSet();
1✔
1609
        for (E[] array : arrays) {
1✔
1610
            union.addAll(Arrays.asList(array));
1✔
1611
        }
1612
        return (E[]) newArrayList(union).toArray();
1✔
1613
    }
1614

1615
    /*
1616
     * Documented, #intersection
1617
     */
1618
    public static <E> List<E> intersection(final List<E> list1, final List<E> list2) {
1619
        final List<E> result = newArrayList();
1✔
1620
        for (final E item : list1) {
1✔
1621
            if (list2.contains(item)) {
1✔
1622
                result.add(item);
1✔
1623
            }
1624
        }
1✔
1625
        return result;
1✔
1626
    }
1627

1628
    @SuppressWarnings("unchecked")
1629
    public static <E> List<E> intersection(final List<E> list, final List<E>... lists) {
1630
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1631
        stack.push(list);
1✔
1632
        for (List<E> es : lists) {
1✔
1633
            stack.push(intersection(stack.peek(), es));
1✔
1634
        }
1635
        return stack.peek();
1✔
1636
    }
1637

1638
    @SuppressWarnings("unchecked")
1639
    public List<T> intersectionWith(final List<T>... lists) {
1640
        return intersection(newArrayList(iterable), lists);
1✔
1641
    }
1642

1643
    @SuppressWarnings("unchecked")
1644
    public static <E> E[] intersection(final E[]... arrays) {
1645
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1646
        stack.push(Arrays.asList(arrays[0]));
1✔
1647
        for (int index = 1; index < arrays.length; index += 1) {
1✔
1648
            stack.push(intersection(stack.peek(), Arrays.asList(arrays[index])));
1✔
1649
        }
1650
        return (E[]) stack.peek().toArray();
1✔
1651
    }
1652

1653
    /*
1654
     * Documented, #difference
1655
     */
1656
    public static <E> List<E> difference(final List<E> list1, final List<E> list2) {
1657
        final List<E> result = newArrayList();
1✔
1658
        for (final E item : list1) {
1✔
1659
            if (!list2.contains(item)) {
1✔
1660
                result.add(item);
1✔
1661
            }
1662
        }
1✔
1663
        return result;
1✔
1664
    }
1665

1666
    @SuppressWarnings("unchecked")
1667
    public static <E> List<E> difference(final List<E> list, final List<E>... lists) {
1668
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1669
        stack.push(list);
1✔
1670
        for (List<E> es : lists) {
1✔
1671
            stack.push(difference(stack.peek(), es));
1✔
1672
        }
1673
        return stack.peek();
1✔
1674
    }
1675

1676
    @SuppressWarnings("unchecked")
1677
    public List<T> differenceWith(final List<T>... lists) {
1678
        return difference(newArrayList(iterable), lists);
1✔
1679
    }
1680

1681
    @SuppressWarnings("unchecked")
1682
    public static <E> E[] difference(final E[]... arrays) {
1683
        final Deque<List<E>> stack = new ArrayDeque<>();
1✔
1684
        stack.push(Arrays.asList(arrays[0]));
1✔
1685
        for (int index = 1; index < arrays.length; index += 1) {
1✔
1686
            stack.push(difference(stack.peek(), Arrays.asList(arrays[index])));
1✔
1687
        }
1688
        return (E[]) stack.peek().toArray();
1✔
1689
    }
1690

1691
    /*
1692
     * Documented, #zip
1693
     */
1694
    @SuppressWarnings("unchecked")
1695
    public static <T> List<List<T>> zip(final List<T>... lists) {
1696
        final List<List<T>> zipped = newArrayList();
1✔
1697
        each(
1✔
1698
                Arrays.asList(lists),
1✔
1699
                list -> {
1700
                    int index = 0;
1✔
1701
                    for (T elem : list) {
1✔
1702
                        final List<T> nTuple =
1703
                                index >= zipped.size()
1✔
1704
                                        ? Underscore.newArrayList()
1✔
1705
                                        : zipped.get(index);
1✔
1706
                        if (index >= zipped.size()) {
1✔
1707
                            zipped.add(nTuple);
1✔
1708
                        }
1709
                        index += 1;
1✔
1710
                        nTuple.add(elem);
1✔
1711
                    }
1✔
1712
                });
1✔
1713
        return zipped;
1✔
1714
    }
1715

1716
    @SuppressWarnings("unchecked")
1717
    public static <T> List<List<T>> unzip(final List<T>... lists) {
1718
        final List<List<T>> unzipped = newArrayList();
1✔
1719
        for (int index = 0; index < lists[0].size(); index += 1) {
1✔
1720
            final List<T> nTuple = newArrayList();
1✔
1721
            for (List<T> list : lists) {
1✔
1722
                nTuple.add(list.get(index));
1✔
1723
            }
1724
            unzipped.add(nTuple);
1✔
1725
        }
1726
        return unzipped;
1✔
1727
    }
1728

1729
    /*
1730
     * Documented, #object
1731
     */
1732
    public static <K, V> List<Map.Entry<K, V>> object(final List<K> keys, final List<V> values) {
1733
        return map(
1✔
1734
                keys,
1735
                new Function<>() {
1✔
1736
                    private int index;
1737

1738
                    @Override
1739
                    public Map.Entry<K, V> apply(K key) {
1740
                        return Map.entry(key, values.get(index++));
1✔
1741
                    }
1742
                });
1743
    }
1744

1745
    public static <E> int findIndex(final List<E> list, final Predicate<E> pred) {
1746
        for (int index = 0; index < list.size(); index++) {
1✔
1747
            if (pred.test(list.get(index))) {
1✔
1748
                return index;
1✔
1749
            }
1750
        }
1751
        return -1;
1✔
1752
    }
1753

1754
    public static <E> int findIndex(final E[] array, final Predicate<E> pred) {
1755
        return findIndex(Arrays.asList(array), pred);
1✔
1756
    }
1757

1758
    public static <E> int findLastIndex(final List<E> list, final Predicate<E> pred) {
1759
        for (int index = list.size() - 1; index >= 0; 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 findLastIndex(final E[] array, final Predicate<E> pred) {
1768
        return findLastIndex(Arrays.asList(array), pred);
1✔
1769
    }
1770

1771
    public static <E extends Comparable<E>> int binarySearch(
1772
            final Iterable<E> iterable, final E key) {
1773
        if (key == null) {
1✔
1774
            return first(iterable) == null ? 0 : -1;
1✔
1775
        }
1776
        int begin = 0;
1✔
1777
        int end = size(iterable) - 1;
1✔
1778
        int numberOfNullValues = 0;
1✔
1779
        List<E> list = new ArrayList<>();
1✔
1780
        for (E item : iterable) {
1✔
1781
            if (item == null) {
1✔
1782
                numberOfNullValues++;
1✔
1783
                end--;
1✔
1784
            } else {
1785
                list.add(item);
1✔
1786
            }
1787
        }
1✔
1788
        while (begin <= end) {
1✔
1789
            int middle = begin + (end - begin) / 2;
1✔
1790
            if (key.compareTo(list.get(middle)) < 0) {
1✔
1791
                end = middle - 1;
1✔
1792
            } else if (key.compareTo(list.get(middle)) > 0) {
1✔
1793
                begin = middle + 1;
1✔
1794
            } else {
1795
                return middle + numberOfNullValues;
1✔
1796
            }
1797
        }
1✔
1798
        return -(begin + numberOfNullValues + 1);
1✔
1799
    }
1800

1801
    public static <E extends Comparable<E>> int binarySearch(final E[] array, final E key) {
1802
        return binarySearch(Arrays.asList(array), key);
1✔
1803
    }
1804

1805
    /*
1806
     * Documented, #sortedIndex
1807
     */
1808
    public static <E extends Comparable<E>> int sortedIndex(final List<E> list, final E value) {
1809
        int index = 0;
1✔
1810
        for (E elem : list) {
1✔
1811
            if (elem.compareTo(value) >= 0) {
1✔
1812
                return index;
1✔
1813
            }
1814
            index += 1;
1✔
1815
        }
1✔
1816
        return -1;
1✔
1817
    }
1818

1819
    public static <E extends Comparable<E>> int sortedIndex(final E[] array, final E value) {
1820
        return sortedIndex(Arrays.asList(array), value);
1✔
1821
    }
1822

1823
    @SuppressWarnings("unchecked")
1824
    public static <E extends Comparable<E>> int sortedIndex(
1825
            final List<E> list, final E value, final String propertyName) {
1826
        try {
1827
            final Field property = value.getClass().getField(propertyName);
1✔
1828
            final Object valueProperty = property.get(value);
1✔
1829
            int index = 0;
1✔
1830
            for (E elem : list) {
1✔
1831
                if (((Comparable) property.get(elem)).compareTo(valueProperty) >= 0) {
1✔
1832
                    return index;
1✔
1833
                }
1834
                index += 1;
1✔
1835
            }
1✔
1836
            return -1;
1✔
1837
        } catch (Exception e) {
1✔
1838
            throw new IllegalArgumentException(e);
1✔
1839
        }
1840
    }
1841

1842
    public static <E extends Comparable<E>> int sortedIndex(
1843
            final E[] array, final E value, final String propertyName) {
1844
        return sortedIndex(Arrays.asList(array), value, propertyName);
1✔
1845
    }
1846

1847
    /*
1848
     * Documented, #indexOf
1849
     */
1850
    public static <E> int indexOf(final List<E> list, final E value) {
1851
        return list.indexOf(value);
1✔
1852
    }
1853

1854
    public static <E> int indexOf(final E[] array, final E value) {
1855
        return indexOf(Arrays.asList(array), value);
1✔
1856
    }
1857

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

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

1869
    /*
1870
     * Documented, #range
1871
     */
1872
    public static List<Integer> range(int stop) {
1873
        return range(0, stop, 1);
1✔
1874
    }
1875

1876
    public static List<Integer> range(int start, int stop) {
1877
        return range(start, stop, start < stop ? 1 : -1);
1✔
1878
    }
1879

1880
    public static List<Integer> range(int start, int stop, int step) {
1881
        List<Integer> list = Underscore.newArrayList();
1✔
1882
        if (step == 0) {
1✔
1883
            return list;
1✔
1884
        }
1885
        if (start < stop) {
1✔
1886
            for (int value = start; value < stop; value += step) {
1✔
1887
                list.add(value);
1✔
1888
            }
1889
        } else {
1890
            for (int value = start; value > stop; value += step) {
1✔
1891
                list.add(value);
1✔
1892
            }
1893
        }
1894
        return list;
1✔
1895
    }
1896

1897
    public static List<Character> range(char stop) {
1898
        return range('a', stop, 1);
1✔
1899
    }
1900

1901
    public static List<Character> range(char start, char stop) {
1902
        return range(start, stop, start < stop ? 1 : -1);
1✔
1903
    }
1904

1905
    public static List<Character> range(char start, char stop, int step) {
1906
        List<Character> list = Underscore.newArrayList();
1✔
1907
        if (step == 0) {
1✔
1908
            return list;
1✔
1909
        }
1910
        if (start < stop) {
1✔
1911
            for (char value = start; value < stop; value += step) {
1✔
1912
                list.add(value);
1✔
1913
            }
1914
        } else {
1915
            for (char value = start; value > stop; value += step) {
1✔
1916
                list.add(value);
1✔
1917
            }
1918
        }
1919
        return list;
1✔
1920
    }
1921

1922
    public static <T> List<List<T>> chunk(final Iterable<T> iterable, final int size) {
1923
        if (size <= 0) {
1✔
1924
            return newArrayList();
1✔
1925
        }
1926
        return chunk(iterable, size, size);
1✔
1927
    }
1928

1929
    public static <T> List<List<T>> chunk(
1930
            final Iterable<T> iterable, final int size, final int step) {
1931
        if (step <= 0 || size < 0) {
1✔
1932
            return newArrayList();
1✔
1933
        }
1934
        int index = 0;
1✔
1935
        int length = size(iterable);
1✔
1936
        final List<List<T>> result = new ArrayList<>(size == 0 ? size : (length / size) + 1);
1✔
1937
        while (index < length) {
1✔
1938
            result.add(newArrayList(iterable).subList(index, Math.min(length, index + size)));
1✔
1939
            index += step;
1✔
1940
        }
1941
        return result;
1✔
1942
    }
1943

1944
    public static <T> List<List<T>> chunkFill(
1945
            final Iterable<T> iterable, final int size, final T fillValue) {
1946
        if (size <= 0) {
1✔
1947
            return newArrayList();
1✔
1948
        }
1949
        return chunkFill(iterable, size, size, fillValue);
1✔
1950
    }
1951

1952
    public static <T> List<List<T>> chunkFill(
1953
            final Iterable<T> iterable, final int size, final int step, final T fillValue) {
1954
        if (step <= 0 || size < 0) {
1✔
1955
            return newArrayList();
1✔
1956
        }
1957
        final List<List<T>> result = chunk(iterable, size, step);
1✔
1958
        int difference = size - result.get(result.size() - 1).size();
1✔
1959
        for (int i = difference; 0 < i; i--) {
1✔
1960
            result.get(result.size() - 1).add(fillValue);
1✔
1961
        }
1962
        return result;
1✔
1963
    }
1964

1965
    public List<List<T>> chunk(final int size) {
1966
        return chunk(getIterable(), size, size);
1✔
1967
    }
1968

1969
    public List<List<T>> chunk(final int size, final int step) {
1970
        return chunk(getIterable(), size, step);
1✔
1971
    }
1972

1973
    public List<List<T>> chunkFill(final int size, final T fillvalue) {
1974
        return chunkFill(getIterable(), size, size, fillvalue);
1✔
1975
    }
1976

1977
    public List<List<T>> chunkFill(final int size, final int step, T fillvalue) {
1978
        return chunkFill(getIterable(), size, step, fillvalue);
1✔
1979
    }
1980

1981
    public static <T> List<T> cycle(final Iterable<T> iterable, final int times) {
1982
        int size = Math.abs(size(iterable) * times);
1✔
1983
        if (size == 0) {
1✔
1984
            return newArrayList();
1✔
1985
        }
1986
        List<T> list = newArrayListWithExpectedSize(size);
1✔
1987
        int round = 0;
1✔
1988
        if (times > 0) {
1✔
1989
            while (round < times) {
1✔
1990
                for (T element : iterable) {
1✔
1991
                    list.add(element);
1✔
1992
                }
1✔
1993
                round++;
1✔
1994
            }
1995
        } else {
1996
            list = cycle(Underscore.reverse(iterable), -times);
1✔
1997
        }
1998
        return list;
1✔
1999
    }
2000

2001
    public List<T> cycle(final int times) {
2002
        return cycle(value(), times);
1✔
2003
    }
2004

2005
    public static <T> List<T> repeat(final T element, final int times) {
2006
        if (times <= 0) {
1✔
2007
            return newArrayList();
1✔
2008
        }
2009
        List<T> result = newArrayListWithExpectedSize(times);
1✔
2010
        for (int i = 0; i < times; i++) {
1✔
2011
            result.add(element);
1✔
2012
        }
2013
        return result;
1✔
2014
    }
2015

2016
    public static <T> List<T> interpose(final Iterable<T> iterable, final T interElement) {
2017
        if (interElement == null) {
1✔
2018
            return newArrayList(iterable);
1✔
2019
        }
2020
        int size = size(iterable);
1✔
2021
        int index = 0;
1✔
2022
        List<T> array = newArrayListWithExpectedSize(size * 2);
1✔
2023
        for (T elem : iterable) {
1✔
2024
            array.add(elem);
1✔
2025
            if (index + 1 < size) {
1✔
2026
                array.add(interElement);
1✔
2027
                index++;
1✔
2028
            }
2029
        }
1✔
2030
        return array;
1✔
2031
    }
2032

2033
    public static <T> List<T> interposeByList(
2034
            final Iterable<T> iterable, final Iterable<T> interIter) {
2035
        if (interIter == null) {
1✔
2036
            return newArrayList(iterable);
1✔
2037
        }
2038
        List<T> interList = newArrayList(interIter);
1✔
2039
        if (isEmpty(interIter)) {
1✔
2040
            return newArrayList(iterable);
1✔
2041
        }
2042
        int size = size(iterable);
1✔
2043
        List<T> array = newArrayListWithExpectedSize(size + interList.size());
1✔
2044
        int index = 0;
1✔
2045
        for (T element : iterable) {
1✔
2046
            array.add(element);
1✔
2047
            if (index < interList.size() && index + 1 < size) {
1✔
2048
                array.add(interList.get(index));
1✔
2049
                index++;
1✔
2050
            }
2051
        }
1✔
2052
        return array;
1✔
2053
    }
2054

2055
    public List<T> interpose(final T element) {
2056
        return interpose(value(), element);
1✔
2057
    }
2058

2059
    public List<T> interposeByList(final Iterable<T> interIter) {
2060
        return interposeByList(value(), interIter);
1✔
2061
    }
2062

2063
    /*
2064
     * Documented, #bind
2065
     */
2066
    public static <T, F> Function<F, T> bind(final Function<F, T> function) {
2067
        return function;
1✔
2068
    }
2069

2070
    /*
2071
     * Documented, #memoize
2072
     */
2073
    public static <T, F> Function<F, T> memoize(final Function<F, T> function) {
2074
        return new MemoizeFunction<>() {
1✔
2075
            @Override
2076
            public T calc(F arg) {
2077
                return function.apply(arg);
1✔
2078
            }
2079
        };
2080
    }
2081

2082
    /*
2083
     * Documented, #delay
2084
     */
2085
    public static <T> java.util.concurrent.ScheduledFuture<T> delay(
2086
            final Supplier<T> function, final int delayMilliseconds) {
2087
        final java.util.concurrent.ScheduledExecutorService scheduler =
2088
                java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
1✔
2089
        final java.util.concurrent.ScheduledFuture<T> future =
1✔
2090
                scheduler.schedule(
1✔
2091
                        function::get,
1✔
2092
                        delayMilliseconds,
2093
                        java.util.concurrent.TimeUnit.MILLISECONDS);
2094
        scheduler.shutdown();
1✔
2095
        return future;
1✔
2096
    }
2097

2098
    public static <T> java.util.concurrent.ScheduledFuture<T> defer(final Supplier<T> function) {
2099
        return delay(function, 0);
1✔
2100
    }
2101

2102
    public static java.util.concurrent.ScheduledFuture<Void> defer(final Runnable runnable) {
2103
        return delay(
1✔
2104
                () -> {
2105
                    runnable.run();
1✔
2106
                    return null;
1✔
2107
                },
2108
                0);
2109
    }
2110

2111
    public static <T> Supplier<T> throttle(final Supplier<T> function, final int waitMilliseconds) {
2112
        class ThrottleLater implements Supplier<T> {
2113
            private final Supplier<T> localFunction;
2114
            private java.util.concurrent.ScheduledFuture<T> timeout;
2115
            private long previous;
2116

2117
            ThrottleLater(final Supplier<T> function) {
1✔
2118
                this.localFunction = function;
1✔
2119
            }
1✔
2120

2121
            @Override
2122
            public T get() {
2123
                previous = now();
1✔
2124
                timeout = null;
1✔
2125
                return localFunction.get();
1✔
2126
            }
2127

2128
            java.util.concurrent.ScheduledFuture<T> getTimeout() {
2129
                return timeout;
1✔
2130
            }
2131

2132
            void setTimeout(java.util.concurrent.ScheduledFuture<T> timeout) {
2133
                this.timeout = timeout;
1✔
2134
            }
1✔
2135

2136
            long getPrevious() {
2137
                return previous;
1✔
2138
            }
2139

2140
            void setPrevious(long previous) {
2141
                this.previous = previous;
1✔
2142
            }
1✔
2143
        }
2144

2145
        class ThrottleFunction implements Supplier<T> {
2146
            private final Supplier<T> localFunction;
2147
            private final ThrottleLater throttleLater;
2148

2149
            ThrottleFunction(final Supplier<T> function) {
1✔
2150
                this.localFunction = function;
1✔
2151
                this.throttleLater = new ThrottleLater(function);
1✔
2152
            }
1✔
2153

2154
            @Override
2155
            public T get() {
2156
                final long now = now();
1✔
2157
                if (throttleLater.getPrevious() == 0L) {
1✔
2158
                    throttleLater.setPrevious(now);
1✔
2159
                }
2160
                final long remaining = waitMilliseconds - (now - throttleLater.getPrevious());
1✔
2161
                T result = null;
1✔
2162
                if (remaining <= 0) {
1✔
2163
                    throttleLater.setPrevious(now);
×
2164
                    result = localFunction.get();
×
2165
                } else if (throttleLater.getTimeout() == null) {
1✔
2166
                    throttleLater.setTimeout(delay(throttleLater, waitMilliseconds));
1✔
2167
                }
2168
                return result;
1✔
2169
            }
2170
        }
2171
        return new ThrottleFunction(function);
1✔
2172
    }
2173

2174
    /*
2175
     * Documented, #debounce
2176
     */
2177
    public static <T> Supplier<T> debounce(
2178
            final Supplier<T> function, final int delayMilliseconds) {
2179
        return new Supplier<>() {
1✔
2180
            private java.util.concurrent.ScheduledFuture<T> timeout;
2181

2182
            @Override
2183
            public T get() {
2184
                clearTimeout(timeout);
1✔
2185
                timeout = delay(function, delayMilliseconds);
1✔
2186
                return null;
1✔
2187
            }
2188
        };
2189
    }
2190

2191
    /*
2192
     * Documented, #wrap
2193
     */
2194
    public static <T> Function<Void, T> wrap(
2195
            final UnaryOperator<T> function, final Function<UnaryOperator<T>, T> wrapper) {
2196
        return arg -> wrapper.apply(function);
1✔
2197
    }
2198

2199
    public static <E> Predicate<E> negate(final Predicate<E> pred) {
2200
        return item -> !pred.test(item);
1✔
2201
    }
2202

2203
    /*
2204
     * Documented, #compose
2205
     */
2206
    @SuppressWarnings("unchecked")
2207
    public static <T> Function<T, T> compose(final Function<T, T>... func) {
2208
        return arg -> {
1✔
2209
            T result = arg;
1✔
2210
            for (int index = func.length - 1; index >= 0; index -= 1) {
1✔
2211
                result = func[index].apply(result);
1✔
2212
            }
2213
            return result;
1✔
2214
        };
2215
    }
2216

2217
    /*
2218
     * Documented, #after
2219
     */
2220
    public static <E> Supplier<E> after(final int count, final Supplier<E> function) {
2221
        class AfterFunction implements Supplier<E> {
2222
            private final int count;
2223
            private final Supplier<E> localFunction;
2224
            private int index;
2225
            private E result;
2226

2227
            AfterFunction(final int count, final Supplier<E> function) {
1✔
2228
                this.count = count;
1✔
2229
                this.localFunction = function;
1✔
2230
            }
1✔
2231

2232
            public E get() {
2233
                if (++index >= count) {
1✔
2234
                    result = localFunction.get();
1✔
2235
                }
2236
                return result;
1✔
2237
            }
2238
        }
2239
        return new AfterFunction(count, function);
1✔
2240
    }
2241

2242
    /*
2243
     * Documented, #before
2244
     */
2245
    public static <E> Supplier<E> before(final int count, final Supplier<E> function) {
2246
        class BeforeFunction implements Supplier<E> {
2247
            private final int count;
2248
            private final Supplier<E> localFunction;
2249
            private int index;
2250
            private E result;
2251

2252
            BeforeFunction(final int count, final Supplier<E> function) {
1✔
2253
                this.count = count;
1✔
2254
                this.localFunction = function;
1✔
2255
            }
1✔
2256

2257
            public E get() {
2258
                if (++index <= count) {
1✔
2259
                    result = localFunction.get();
1✔
2260
                }
2261
                return result;
1✔
2262
            }
2263
        }
2264
        return new BeforeFunction(count, function);
1✔
2265
    }
2266

2267
    /*
2268
     * Documented, #once
2269
     */
2270
    public static <T> Supplier<T> once(final Supplier<T> function) {
2271
        return new Supplier<>() {
1✔
2272
            private volatile boolean executed;
2273
            private T result;
2274

2275
            @Override
2276
            public T get() {
2277
                if (!executed) {
1✔
2278
                    executed = true;
1✔
2279
                    result = function.get();
1✔
2280
                }
2281
                return result;
1✔
2282
            }
2283
        };
2284
    }
2285

2286
    /*
2287
     * Documented, #keys
2288
     */
2289
    public static <K, V> Set<K> keys(final Map<K, V> object) {
2290
        return object.keySet();
1✔
2291
    }
2292

2293
    /*
2294
     * Documented, #values
2295
     */
2296
    public static <K, V> Collection<V> values(final Map<K, V> object) {
2297
        return object.values();
1✔
2298
    }
2299

2300
    public static <K, V> List<Map.Entry<K, V>> mapObject(
2301
            final Map<K, V> object, final Function<? super V, V> func) {
2302
        return map(
1✔
2303
                newArrayList(object.entrySet()),
1✔
2304
                entry -> Map.entry(entry.getKey(), func.apply(entry.getValue())));
1✔
2305
    }
2306

2307
    /*
2308
     * Documented, #pairs
2309
     */
2310
    public static <K, V> List<Map.Entry<K, V>> pairs(final Map<K, V> object) {
2311
        return map(
1✔
2312
                newArrayList(object.entrySet()),
1✔
2313
                entry -> Map.entry(entry.getKey(), entry.getValue()));
1✔
2314
    }
2315

2316
    /*
2317
     * Documented, #invert
2318
     */
2319
    public static <K, V> List<Map.Entry<V, K>> invert(final Map<K, V> object) {
2320
        return map(
1✔
2321
                newArrayList(object.entrySet()),
1✔
2322
                entry -> Map.entry(entry.getValue(), entry.getKey()));
1✔
2323
    }
2324

2325
    /*
2326
     * Documented, #functions
2327
     */
2328
    public static List<String> functions(final Object object) {
2329
        final List<String> result = newArrayList();
1✔
2330
        for (final Method method : object.getClass().getDeclaredMethods()) {
1✔
2331
            result.add(method.getName());
1✔
2332
        }
2333
        return sort(uniq(result));
1✔
2334
    }
2335

2336
    public static List<String> methods(final Object object) {
2337
        return functions(object);
1✔
2338
    }
2339

2340
    /*
2341
     * Documented, #extend
2342
     */
2343
    @SuppressWarnings("unchecked")
2344
    public static <K, V> Map<K, V> extend(final Map<K, V> destination, final Map<K, V>... sources) {
2345
        final Map<K, V> result = newLinkedHashMap();
1✔
2346
        result.putAll(destination);
1✔
2347
        for (final Map<K, V> source : sources) {
1✔
2348
            result.putAll(source);
1✔
2349
        }
2350
        return result;
1✔
2351
    }
2352

2353
    public static <E> E findKey(final List<E> list, final Predicate<E> pred) {
2354
        for (E e : list) {
1✔
2355
            if (pred.test(e)) {
1✔
2356
                return e;
1✔
2357
            }
2358
        }
1✔
2359
        return null;
1✔
2360
    }
2361

2362
    public static <E> E findKey(final E[] array, final Predicate<E> pred) {
2363
        return findKey(Arrays.asList(array), pred);
1✔
2364
    }
2365

2366
    public static <E> E findLastKey(final List<E> list, final Predicate<E> pred) {
2367
        for (int index = list.size() - 1; index >= 0; index--) {
1✔
2368
            if (pred.test(list.get(index))) {
1✔
2369
                return list.get(index);
1✔
2370
            }
2371
        }
2372
        return null;
1✔
2373
    }
2374

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

2379
    /*
2380
     * Documented, #pick
2381
     */
2382
    @SuppressWarnings("unchecked")
2383
    public static <K, V> List<Map.Entry<K, V>> pick(final Map<K, V> object, final K... keys) {
2384
        return without(
1✔
2385
                map(
1✔
2386
                        newArrayList(object.entrySet()),
1✔
2387
                        entry -> {
2388
                            if (Arrays.asList(keys).contains(entry.getKey())) {
1✔
2389
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2390
                            } else {
2391
                                return null;
1✔
2392
                            }
2393
                        }),
2394
                (Map.Entry<K, V>) null);
2395
    }
2396

2397
    @SuppressWarnings("unchecked")
2398
    public static <K, V> List<Map.Entry<K, V>> pick(
2399
            final Map<K, V> object, final Predicate<V> pred) {
2400
        return without(
1✔
2401
                map(
1✔
2402
                        newArrayList(object.entrySet()),
1✔
2403
                        entry -> {
2404
                            if (pred.test(object.get(entry.getKey()))) {
1✔
2405
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2406
                            } else {
2407
                                return null;
1✔
2408
                            }
2409
                        }),
2410
                (Map.Entry<K, V>) null);
2411
    }
2412

2413
    /*
2414
     * Documented, #omit
2415
     */
2416
    @SuppressWarnings("unchecked")
2417
    public static <K, V> List<Map.Entry<K, V>> omit(final Map<K, V> object, final K... keys) {
2418
        return without(
1✔
2419
                map(
1✔
2420
                        newArrayList(object.entrySet()),
1✔
2421
                        entry -> {
2422
                            if (Arrays.asList(keys).contains(entry.getKey())) {
1✔
2423
                                return null;
1✔
2424
                            } else {
2425
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2426
                            }
2427
                        }),
2428
                (Map.Entry<K, V>) null);
2429
    }
2430

2431
    @SuppressWarnings("unchecked")
2432
    public static <K, V> List<Map.Entry<K, V>> omit(
2433
            final Map<K, V> object, final Predicate<V> pred) {
2434
        return without(
1✔
2435
                map(
1✔
2436
                        newArrayList(object.entrySet()),
1✔
2437
                        entry -> {
2438
                            if (pred.test(entry.getValue())) {
1✔
2439
                                return null;
1✔
2440
                            } else {
2441
                                return Map.entry(entry.getKey(), entry.getValue());
1✔
2442
                            }
2443
                        }),
2444
                (Map.Entry<K, V>) null);
2445
    }
2446

2447
    /*
2448
     * Documented, #defaults
2449
     */
2450
    public static <K, V> Map<K, V> defaults(final Map<K, V> object, final Map<K, V> defaults) {
2451
        final Map<K, V> result = newLinkedHashMap();
1✔
2452
        result.putAll(defaults);
1✔
2453
        result.putAll(object);
1✔
2454
        return result;
1✔
2455
    }
2456

2457
    /*
2458
     * Documented, #clone
2459
     */
2460
    public static Object clone(final Object obj) {
2461
        try {
2462
            if (obj instanceof Cloneable) {
1✔
2463
                for (final Method method : obj.getClass().getMethods()) {
1✔
2464
                    if (method.getName().equals("clone")
1✔
2465
                            && method.getParameterTypes().length == 0) {
1✔
2466
                        return method.invoke(obj);
1✔
2467
                    }
2468
                }
2469
            }
2470
        } catch (Exception e) {
1✔
2471
            throw new IllegalArgumentException(e);
1✔
2472
        }
1✔
2473
        throw new IllegalArgumentException("Cannot clone object");
1✔
2474
    }
2475

2476
    @SuppressWarnings("unchecked")
2477
    public static <E> E[] clone(final E... iterable) {
2478
        return Arrays.copyOf(iterable, iterable.length);
1✔
2479
    }
2480

2481
    public static <T> void tap(final Iterable<T> iterable, final Consumer<? super T> func) {
2482
        each(iterable, func);
1✔
2483
    }
1✔
2484

2485
    public static <K, V> boolean isMatch(final Map<K, V> object, final Map<K, V> properties) {
2486
        for (final K key : keys(properties)) {
1✔
2487
            if (!object.containsKey(key) || !object.get(key).equals(properties.get(key))) {
1✔
2488
                return false;
1✔
2489
            }
2490
        }
1✔
2491
        return true;
1✔
2492
    }
2493

2494
    /*
2495
     * Documented, #isEqual
2496
     */
2497
    public static boolean isEqual(final Object object, final Object other) {
2498
        return Objects.equals(object, other);
1✔
2499
    }
2500

2501
    public static <K, V> boolean isEmpty(final Map<K, V> object) {
2502
        return object == null || object.isEmpty();
1✔
2503
    }
2504

2505
    /*
2506
     * Documented, #isEmpty
2507
     */
2508
    public static <T> boolean isEmpty(final Iterable<T> iterable) {
2509
        return iterable == null || !iterable.iterator().hasNext();
1✔
2510
    }
2511

2512
    public boolean isEmpty() {
2513
        return iterable == null || !iterable.iterator().hasNext();
1✔
2514
    }
2515

2516
    public static <K, V> boolean isNotEmpty(final Map<K, V> object) {
2517
        return object != null && !object.isEmpty();
1✔
2518
    }
2519

2520
    public static <T> boolean isNotEmpty(final Iterable<T> iterable) {
2521
        return iterable != null && iterable.iterator().hasNext();
1✔
2522
    }
2523

2524
    public boolean isNotEmpty() {
2525
        return iterable != null && iterable.iterator().hasNext();
1✔
2526
    }
2527

2528
    /*
2529
     * Documented, #isArray
2530
     */
2531
    public static boolean isArray(final Object object) {
2532
        return object != null && object.getClass().isArray();
1✔
2533
    }
2534

2535
    /*
2536
     * Documented, #isObject
2537
     */
2538
    public static boolean isObject(final Object object) {
2539
        return object instanceof Map;
1✔
2540
    }
2541

2542
    /*
2543
     * Documented, #isFunction
2544
     */
2545
    public static boolean isFunction(final Object object) {
2546
        return object instanceof Function;
1✔
2547
    }
2548

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

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

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

2570
    public static boolean isRegExp(final Object object) {
2571
        return object instanceof java.util.regex.Pattern;
1✔
2572
    }
2573

2574
    public static boolean isError(final Object object) {
2575
        return object instanceof Throwable;
1✔
2576
    }
2577

2578
    /*
2579
     * Documented, #isBoolean
2580
     */
2581
    public static boolean isBoolean(final Object object) {
2582
        return object instanceof Boolean;
1✔
2583
    }
2584

2585
    public static boolean isNull(final Object object) {
2586
        return object == null;
1✔
2587
    }
2588

2589
    /*
2590
     * Documented, #has
2591
     */
2592
    public static <K, V> boolean has(final Map<K, V> object, final K key) {
2593
        return object.containsKey(key);
1✔
2594
    }
2595

2596
    public static <E> E identity(final E value) {
2597
        return value;
1✔
2598
    }
2599

2600
    public static <E> Supplier<E> constant(final E value) {
2601
        return () -> value;
1✔
2602
    }
2603

2604
    public static <K, V> Function<Map<K, V>, V> property(final K key) {
2605
        return object -> object.get(key);
1✔
2606
    }
2607

2608
    public static <K, V> Function<K, V> propertyOf(final Map<K, V> object) {
2609
        return object::get;
1✔
2610
    }
2611

2612
    public static <K, V> Predicate<Map<K, V>> matcher(final Map<K, V> object) {
2613
        return item -> {
1✔
2614
            for (final K key : keys(object)) {
1✔
2615
                if (!item.containsKey(key) || !item.get(key).equals(object.get(key))) {
1✔
2616
                    return false;
1✔
2617
                }
2618
            }
1✔
2619
            return true;
1✔
2620
        };
2621
    }
2622

2623
    /*
2624
     * Documented, #times
2625
     */
2626
    public static void times(final int count, final Runnable runnable) {
2627
        for (int index = 0; index < count; index += 1) {
1✔
2628
            runnable.run();
1✔
2629
        }
2630
    }
1✔
2631

2632
    /*
2633
     * Documented, #random
2634
     */
2635
    public static int random(final int min, final int max) {
2636
        return min + new java.security.SecureRandom().nextInt(max - min + 1);
1✔
2637
    }
2638

2639
    public static int random(final int max) {
2640
        return new java.security.SecureRandom().nextInt(max + 1);
1✔
2641
    }
2642

2643
    public static long now() {
2644
        return new Date().getTime();
1✔
2645
    }
2646

2647
    /*
2648
     * Documented, #escape
2649
     */
2650
    public static String escape(final String value) {
2651
        final StringBuilder builder = new StringBuilder();
1✔
2652
        for (final char ch : value.toCharArray()) {
1✔
2653
            builder.append(ESCAPES.containsKey(ch) ? ESCAPES.get(ch) : ch);
1✔
2654
        }
2655
        return builder.toString();
1✔
2656
    }
2657

2658
    public static String unescape(final String value) {
2659
        return value.replace("&#x60;", "`")
1✔
2660
                .replace("&#x27;", "'")
1✔
2661
                .replace("&lt;", "<")
1✔
2662
                .replace("&gt;", ">")
1✔
2663
                .replace("&quot;", "\"")
1✔
2664
                .replace("&amp;", "&");
1✔
2665
    }
2666

2667
    /*
2668
     * Documented, #result
2669
     */
2670
    public static <E> Object result(final Iterable<E> iterable, final Predicate<E> pred) {
2671
        for (E element : iterable) {
1✔
2672
            if (pred.test(element)) {
1✔
2673
                if (element instanceof Map.Entry) {
1✔
2674
                    if (((Map.Entry) element).getValue() instanceof Supplier) {
1✔
2675
                        return ((Supplier) ((Map.Entry) element).getValue()).get();
1✔
2676
                    }
2677
                    return ((Map.Entry) element).getValue();
1✔
2678
                }
2679
                return element;
1✔
2680
            }
2681
        }
1✔
2682
        return null;
1✔
2683
    }
2684

2685
    /*
2686
     * Documented, #uniqueId
2687
     */
2688
    public static String uniqueId(final String prefix) {
2689
        return (prefix == null ? "" : prefix) + UNIQUE_ID.incrementAndGet();
1✔
2690
    }
2691

2692
    /*
2693
     * Documented, #uniquePassword
2694
     */
2695
    public static String uniquePassword() {
2696
        final String[] passwords =
1✔
2697
                new String[] {
2698
                    "ALKJVBPIQYTUIWEBVPQALZVKQRWORTUYOYISHFLKAJMZNXBVMNFGAHKJSDFALAPOQIERIUYTGSFGKMZNXBVJAHGFAKX",
2699
                    "1234567890",
2700
                    "qpowiealksdjzmxnvbfghsdjtreiuowiruksfhksajmzxncbvlaksjdhgqwetytopskjhfgvbcnmzxalksjdfhgbvzm",
2701
                    ".@,-+/()#$%^&*!"
2702
                };
2703
        final StringBuilder result = new StringBuilder();
1✔
2704
        final long passwordLength =
2705
                Math.abs(UUID.randomUUID().getLeastSignificantBits() % MIN_PASSWORD_LENGTH_8)
1✔
2706
                        + MIN_PASSWORD_LENGTH_8;
2707
        for (int index = 0; index < passwordLength; index += 1) {
1✔
2708
            final int passIndex = (int) (passwords.length * (long) index / passwordLength);
1✔
2709
            final int charIndex =
2710
                    (int)
2711
                            Math.abs(
1✔
2712
                                    UUID.randomUUID().getLeastSignificantBits()
1✔
2713
                                            % passwords[passIndex].length());
1✔
2714
            result.append(passwords[passIndex].charAt(charIndex));
1✔
2715
        }
2716
        return result.toString();
1✔
2717
    }
2718

2719
    public static <K, V> Template<Map<K, V>> template(final String template) {
2720
        return new TemplateImpl<>(template);
1✔
2721
    }
2722

2723
    public static String format(final String template, final Object... params) {
2724
        final java.util.regex.Matcher matcher = FORMAT_PATTERN.matcher(template);
1✔
2725
        final StringBuffer buffer = new StringBuffer();
1✔
2726
        int index = 0;
1✔
2727
        while (matcher.find()) {
1✔
2728
            if (matcher.group(1).isEmpty()) {
1✔
2729
                matcher.appendReplacement(buffer, "<%" + index++ + "%>");
1✔
2730
            } else {
2731
                matcher.appendReplacement(buffer, "<%" + matcher.group(1) + "%>");
1✔
2732
            }
2733
        }
2734
        matcher.appendTail(buffer);
1✔
2735
        final String newTemplate = buffer.toString();
1✔
2736
        final Map<Integer, String> args = newLinkedHashMap();
1✔
2737
        index = 0;
1✔
2738
        for (Object param : params) {
1✔
2739
            args.put(index, param.toString());
1✔
2740
            index += 1;
1✔
2741
        }
2742
        return new TemplateImpl<Integer, String>(newTemplate).apply(args);
1✔
2743
    }
2744

2745
    public static <T> Iterable<T> iterate(final T seed, final UnaryOperator<T> unaryOperator) {
2746
        return new MyIterable<>(seed, unaryOperator);
1✔
2747
    }
2748

2749
    /*
2750
     * Documented, #chain
2751
     */
2752
    public static <T> Chain<T> chain(final List<T> list) {
2753
        return new Underscore.Chain<>(list);
1✔
2754
    }
2755

2756
    public static Chain<Map<String, Object>> chain(final Map<String, Object> map) {
2757
        return new Underscore.Chain<>(map);
1✔
2758
    }
2759

2760
    public static <T> Chain<T> chain(final Iterable<T> iterable) {
2761
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2762
    }
2763

2764
    public static <T> Chain<T> chain(final Iterable<T> iterable, int size) {
2765
        return new Underscore.Chain<>(newArrayList(iterable, size));
1✔
2766
    }
2767

2768
    @SuppressWarnings("unchecked")
2769
    public static <T> Chain<T> chain(final T... array) {
2770
        return new Underscore.Chain<>(Arrays.asList(array));
1✔
2771
    }
2772

2773
    public static Chain<Integer> chain(final int[] array) {
2774
        return new Underscore.Chain<>(newIntegerList(array));
1✔
2775
    }
2776

2777
    public Chain<T> chain() {
2778
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2779
    }
2780

2781
    public static <T> Chain<T> of(final List<T> list) {
2782
        return new Underscore.Chain<>(list);
1✔
2783
    }
2784

2785
    public static <T> Chain<T> of(final Iterable<T> iterable) {
2786
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2787
    }
2788

2789
    public static <T> Chain<T> of(final Iterable<T> iterable, int size) {
2790
        return new Underscore.Chain<>(newArrayList(iterable, size));
1✔
2791
    }
2792

2793
    @SuppressWarnings("unchecked")
2794
    public static <T> Chain<T> of(final T... array) {
2795
        return new Underscore.Chain<>(Arrays.asList(array));
1✔
2796
    }
2797

2798
    public static Chain<Integer> of(final int[] array) {
2799
        return new Underscore.Chain<>(newIntegerList(array));
1✔
2800
    }
2801

2802
    public Chain<T> of() {
2803
        return new Underscore.Chain<>(newArrayList(iterable));
1✔
2804
    }
2805

2806
    public static class Chain<T> {
2807
        private final T item;
2808
        private final List<T> list;
2809
        private final Map<String, Object> map;
2810

2811
        public Chain(final T item) {
1✔
2812
            this.item = item;
1✔
2813
            this.list = null;
1✔
2814
            this.map = null;
1✔
2815
        }
1✔
2816

2817
        public Chain(final List<T> list) {
1✔
2818
            this.item = null;
1✔
2819
            this.list = list;
1✔
2820
            this.map = null;
1✔
2821
        }
1✔
2822

2823
        public Chain(final Map<String, Object> map) {
1✔
2824
            this.item = null;
1✔
2825
            this.list = null;
1✔
2826
            this.map = map;
1✔
2827
        }
1✔
2828

2829
        public Chain<T> first() {
2830
            return new Chain<>(Underscore.first(list));
1✔
2831
        }
2832

2833
        public Chain<T> first(int n) {
2834
            return new Chain<>(Underscore.first(list, n));
1✔
2835
        }
2836

2837
        public Chain<T> first(final Predicate<T> pred) {
2838
            return new Chain<>(Underscore.first(list, pred));
1✔
2839
        }
2840

2841
        public Chain<T> first(final Predicate<T> pred, int n) {
2842
            return new Chain<>(Underscore.first(list, pred, n));
1✔
2843
        }
2844

2845
        public Chain<T> firstOrNull() {
2846
            return new Chain<>(Underscore.firstOrNull(list));
1✔
2847
        }
2848

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

2853
        public Chain<T> initial() {
2854
            return new Chain<>(Underscore.initial(list));
1✔
2855
        }
2856

2857
        public Chain<T> initial(int n) {
2858
            return new Chain<>(Underscore.initial(list, n));
1✔
2859
        }
2860

2861
        public Chain<T> last() {
2862
            return new Chain<>(Underscore.last(list));
1✔
2863
        }
2864

2865
        public Chain<T> last(int n) {
2866
            return new Chain<>(Underscore.last(list, n));
1✔
2867
        }
2868

2869
        public Chain<T> lastOrNull() {
2870
            return new Chain<>(Underscore.lastOrNull(list));
1✔
2871
        }
2872

2873
        public Chain<T> lastOrNull(final Predicate<T> pred) {
2874
            return new Chain<>(Underscore.lastOrNull(list, pred));
1✔
2875
        }
2876

2877
        public Chain<T> rest() {
2878
            return new Chain<>(Underscore.rest(list));
1✔
2879
        }
2880

2881
        public Chain<T> rest(int n) {
2882
            return new Chain<>(Underscore.rest(list, n));
1✔
2883
        }
2884

2885
        public Chain<T> compact() {
2886
            return new Chain<>(Underscore.compact(list));
1✔
2887
        }
2888

2889
        public Chain<T> compact(final T falsyValue) {
2890
            return new Chain<>(Underscore.compact(list, falsyValue));
1✔
2891
        }
2892

2893
        @SuppressWarnings("unchecked")
2894
        public Chain flatten() {
2895
            return new Chain<>(Underscore.flatten(list));
1✔
2896
        }
2897

2898
        public <F> Chain<F> map(final Function<? super T, F> func) {
2899
            return new Chain<>(Underscore.map(list, func));
1✔
2900
        }
2901

2902
        public <F> Chain<F> mapMulti(final BiConsumer<? super T, ? super Consumer<F>> mapper) {
2903
            return new Chain<>(Underscore.mapMulti(list, mapper));
1✔
2904
        }
2905

2906
        public <F> Chain<F> mapIndexed(final BiFunction<Integer, ? super T, F> func) {
2907
            return new Chain<>(Underscore.mapIndexed(list, func));
1✔
2908
        }
2909

2910
        public Chain<T> replace(final Predicate<T> pred, final T value) {
2911
            return new Chain<>(Underscore.replace(list, pred, value));
1✔
2912
        }
2913

2914
        public Chain<T> replaceIndexed(final PredicateIndexed<T> pred, final T value) {
2915
            return new Chain<>(Underscore.replaceIndexed(list, pred, value));
1✔
2916
        }
2917

2918
        public Chain<T> filter(final Predicate<T> pred) {
2919
            return new Chain<>(Underscore.filter(list, pred));
1✔
2920
        }
2921

2922
        public Chain<T> filterIndexed(final PredicateIndexed<T> pred) {
2923
            return new Chain<>(Underscore.filterIndexed(list, pred));
1✔
2924
        }
2925

2926
        public Chain<T> reject(final Predicate<T> pred) {
2927
            return new Chain<>(Underscore.reject(list, pred));
1✔
2928
        }
2929

2930
        public Chain<T> rejectIndexed(final PredicateIndexed<T> pred) {
2931
            return new Chain<>(Underscore.rejectIndexed(list, pred));
1✔
2932
        }
2933

2934
        public Chain<T> filterFalse(final Predicate<T> pred) {
2935
            return new Chain<>(Underscore.reject(list, pred));
1✔
2936
        }
2937

2938
        public <F> Chain<F> reduce(final BiFunction<F, T, F> func, final F zeroElem) {
2939
            return new Chain<>(Underscore.reduce(list, func, zeroElem));
1✔
2940
        }
2941

2942
        public Chain<Optional<T>> reduce(final BinaryOperator<T> func) {
2943
            return new Chain<>(Underscore.reduce(list, func));
1✔
2944
        }
2945

2946
        public <F> Chain<F> reduceRight(final BiFunction<F, T, F> func, final F zeroElem) {
2947
            return new Chain<>(Underscore.reduceRight(list, func, zeroElem));
1✔
2948
        }
2949

2950
        public Chain<Optional<T>> reduceRight(final BinaryOperator<T> func) {
2951
            return new Chain<>(Underscore.reduceRight(list, func));
1✔
2952
        }
2953

2954
        public Chain<Optional<T>> find(final Predicate<T> pred) {
2955
            return new Chain<>(Underscore.find(list, pred));
1✔
2956
        }
2957

2958
        public Chain<Optional<T>> findLast(final Predicate<T> pred) {
2959
            return new Chain<>(Underscore.findLast(list, pred));
1✔
2960
        }
2961

2962
        @SuppressWarnings("unchecked")
2963
        public Chain<Comparable> max() {
2964
            return new Chain<>(Underscore.max((Collection) list));
1✔
2965
        }
2966

2967
        public <F extends Comparable<? super F>> Chain<T> max(final Function<T, F> func) {
2968
            return new Chain<>(Underscore.max(list, func));
1✔
2969
        }
2970

2971
        @SuppressWarnings("unchecked")
2972
        public Chain<Comparable> min() {
2973
            return new Chain<>(Underscore.min((Collection) list));
1✔
2974
        }
2975

2976
        public <F extends Comparable<? super F>> Chain<T> min(final Function<T, F> func) {
2977
            return new Chain<>(Underscore.min(list, func));
1✔
2978
        }
2979

2980
        @SuppressWarnings("unchecked")
2981
        public Chain<Comparable> sort() {
2982
            return new Chain<>(Underscore.sort((List<Comparable>) list));
1✔
2983
        }
2984

2985
        @SuppressWarnings("unchecked")
2986
        public <F extends Comparable<? super F>> Chain<F> sortWith(final Comparator<F> comparator) {
2987
            return new Chain<>(Underscore.sortWith((List<F>) list, comparator));
1✔
2988
        }
2989

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

2994
        @SuppressWarnings("unchecked")
2995
        public <K> Chain<Map<K, Comparable>> sortBy(final K key) {
2996
            return new Chain<>(Underscore.sortBy((List<Map<K, Comparable>>) list, key));
1✔
2997
        }
2998

2999
        public <F> Chain<Map<F, List<T>>> groupBy(final Function<T, F> func) {
3000
            return new Chain<>(Underscore.groupBy(list, func));
1✔
3001
        }
3002

3003
        public <F> Chain<Map<F, Optional<T>>> groupBy(
3004
                final Function<T, F> func, final BinaryOperator<T> binaryOperator) {
3005
            return new Chain<>(Underscore.groupBy(list, func, binaryOperator));
1✔
3006
        }
3007

3008
        public Chain<Map<Object, List<T>>> indexBy(final String property) {
3009
            return new Chain<>(Underscore.indexBy(list, property));
1✔
3010
        }
3011

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

3016
        public Chain<Map<T, Integer>> countBy() {
3017
            return new Chain<>(Underscore.countBy(list));
1✔
3018
        }
3019

3020
        public Chain<T> shuffle() {
3021
            return new Chain<>(Underscore.shuffle(list));
1✔
3022
        }
3023

3024
        public Chain<T> sample() {
3025
            return new Chain<>(Underscore.sample(list));
1✔
3026
        }
3027

3028
        public Chain<T> sample(final int howMany) {
3029
            return new Chain<>(Underscore.newArrayList(Underscore.sample(list, howMany)));
1✔
3030
        }
3031

3032
        public Chain<T> tap(final Consumer<T> func) {
3033
            Underscore.each(list, func);
1✔
3034
            return new Chain<>(list);
1✔
3035
        }
3036

3037
        public Chain<T> forEach(final Consumer<T> func) {
3038
            return tap(func);
1✔
3039
        }
3040

3041
        public Chain<T> forEachRight(final Consumer<T> func) {
3042
            Underscore.eachRight(list, func);
1✔
3043
            return new Chain<>(list);
1✔
3044
        }
3045

3046
        public Chain<Boolean> every(final Predicate<T> pred) {
3047
            return new Chain<>(Underscore.every(list, pred));
1✔
3048
        }
3049

3050
        public Chain<Boolean> some(final Predicate<T> pred) {
3051
            return new Chain<>(Underscore.some(list, pred));
1✔
3052
        }
3053

3054
        public Chain<Integer> count(final Predicate<T> pred) {
3055
            return new Chain<>(Underscore.count(list, pred));
1✔
3056
        }
3057

3058
        public Chain<Boolean> contains(final T elem) {
3059
            return new Chain<>(Underscore.contains(list, elem));
1✔
3060
        }
3061

3062
        public Chain<Boolean> containsWith(final T elem) {
3063
            return new Chain<>(Underscore.containsWith(list, elem));
1✔
3064
        }
3065

3066
        public Chain<T> invoke(final String methodName, final List<Object> args) {
3067
            return new Chain<>(Underscore.invoke(list, methodName, args));
1✔
3068
        }
3069

3070
        public Chain<T> invoke(final String methodName) {
3071
            return new Chain<>(Underscore.invoke(list, methodName));
1✔
3072
        }
3073

3074
        public Chain<Object> pluck(final String propertyName) {
3075
            return new Chain<>(Underscore.pluck(list, propertyName));
1✔
3076
        }
3077

3078
        public <E> Chain<T> where(final List<Map.Entry<String, E>> properties) {
3079
            return new Chain<>(Underscore.where(list, properties));
1✔
3080
        }
3081

3082
        public <E> Chain<Optional<T>> findWhere(final List<Map.Entry<String, E>> properties) {
3083
            return new Chain<>(Underscore.findWhere(list, properties));
1✔
3084
        }
3085

3086
        public Chain<T> uniq() {
3087
            return new Chain<>(Underscore.uniq(list));
1✔
3088
        }
3089

3090
        public <F> Chain<T> uniq(final Function<T, F> func) {
3091
            return new Chain<>(Underscore.newArrayList(Underscore.uniq(list, func)));
1✔
3092
        }
3093

3094
        public Chain<T> distinct() {
3095
            return new Chain<>(Underscore.uniq(list));
1✔
3096
        }
3097

3098
        @SuppressWarnings("unchecked")
3099
        public <F> Chain<F> distinctBy(final Function<T, F> func) {
3100
            return new Chain<>(Underscore.newArrayList((Iterable<F>) Underscore.uniq(list, func)));
1✔
3101
        }
3102

3103
        @SuppressWarnings("unchecked")
3104
        public Chain<T> union(final List<T>... lists) {
3105
            return new Chain<>(Underscore.union(list, lists));
1✔
3106
        }
3107

3108
        @SuppressWarnings("unchecked")
3109
        public Chain<T> intersection(final List<T>... lists) {
3110
            return new Chain<>(Underscore.intersection(list, lists));
1✔
3111
        }
3112

3113
        @SuppressWarnings("unchecked")
3114
        public Chain<T> difference(final List<T>... lists) {
3115
            return new Chain<>(Underscore.difference(list, lists));
1✔
3116
        }
3117

3118
        public Chain<Integer> range(final int stop) {
3119
            return new Chain<>(Underscore.range(stop));
1✔
3120
        }
3121

3122
        public Chain<Integer> range(final int start, final int stop) {
3123
            return new Chain<>(Underscore.range(start, stop));
1✔
3124
        }
3125

3126
        public Chain<Integer> range(final int start, final int stop, final int step) {
3127
            return new Chain<>(Underscore.range(start, stop, step));
1✔
3128
        }
3129

3130
        public Chain<List<T>> chunk(final int size) {
3131
            return new Chain<>(Underscore.chunk(value(), size, size));
1✔
3132
        }
3133

3134
        public Chain<List<T>> chunk(final int size, final int step) {
3135
            return new Chain<>(Underscore.chunk(value(), size, step));
1✔
3136
        }
3137

3138
        public Chain<List<T>> chunkFill(final int size, final T fillValue) {
3139
            return new Chain<>(Underscore.chunkFill(value(), size, size, fillValue));
1✔
3140
        }
3141

3142
        public Chain<List<T>> chunkFill(final int size, final int step, final T fillValue) {
3143
            return new Chain<>(Underscore.chunkFill(value(), size, step, fillValue));
1✔
3144
        }
3145

3146
        public Chain<T> cycle(final int times) {
3147
            return new Chain<>(Underscore.cycle(value(), times));
1✔
3148
        }
3149

3150
        public Chain<T> interpose(final T element) {
3151
            return new Chain<>(Underscore.interpose(value(), element));
1✔
3152
        }
3153

3154
        public Chain<T> interposeByList(final Iterable<T> interIter) {
3155
            return new Chain<>(Underscore.interposeByList(value(), interIter));
1✔
3156
        }
3157

3158
        @SuppressWarnings("unchecked")
3159
        public Chain<T> concat(final List<T>... lists) {
3160
            return new Chain<>(Underscore.concat(list, lists));
1✔
3161
        }
3162

3163
        public Chain<T> slice(final int start) {
3164
            return new Chain<>(Underscore.slice(list, start));
1✔
3165
        }
3166

3167
        public Chain<T> slice(final int start, final int end) {
3168
            return new Chain<>(Underscore.slice(list, start, end));
1✔
3169
        }
3170

3171
        public Chain<List<T>> splitAt(final int position) {
3172
            return new Chain<>(Underscore.splitAt(list, position));
1✔
3173
        }
3174

3175
        public Chain<T> takeSkipping(final int stepSize) {
3176
            return new Chain<>(Underscore.takeSkipping(list, stepSize));
1✔
3177
        }
3178

3179
        public Chain<T> reverse() {
3180
            return new Chain<>(Underscore.reverse(list));
1✔
3181
        }
3182

3183
        public Chain<String> join() {
3184
            return new Chain<>(Underscore.join(list));
1✔
3185
        }
3186

3187
        public Chain<String> join(final String separator) {
3188
            return new Chain<>(Underscore.join(list, separator));
1✔
3189
        }
3190

3191
        @SuppressWarnings("unchecked")
3192
        public Chain<T> push(final T... values) {
3193
            return new Chain<>(Underscore.push(value(), values));
1✔
3194
        }
3195

3196
        public Chain<Map.Entry<T, List<T>>> pop() {
3197
            return new Chain<>(Underscore.pop(value()));
1✔
3198
        }
3199

3200
        public Chain<Map.Entry<T, List<T>>> shift() {
3201
            return new Chain<>(Underscore.shift(value()));
1✔
3202
        }
3203

3204
        @SuppressWarnings("unchecked")
3205
        public Chain<T> unshift(final T... values) {
3206
            return new Chain<>(Underscore.unshift(value(), values));
1✔
3207
        }
3208

3209
        public Chain<T> skip(final int numberToSkip) {
3210
            return new Chain<>(list.subList(numberToSkip, list.size()));
1✔
3211
        }
3212

3213
        public Chain<T> limit(final int size) {
3214
            return new Chain<>(Underscore.first(list, size));
1✔
3215
        }
3216

3217
        @SuppressWarnings("unchecked")
3218
        public <K, V> Chain<Map<K, V>> toMap() {
3219
            return new Chain<>(Underscore.toMap((Iterable<Map.Entry<K, V>>) list));
1✔
3220
        }
3221

3222
        public boolean isEmpty() {
3223
            return Underscore.isEmpty(list);
1✔
3224
        }
3225

3226
        public boolean isNotEmpty() {
3227
            return Underscore.isNotEmpty(list);
1✔
3228
        }
3229

3230
        public int size() {
3231
            return Underscore.size(list);
1✔
3232
        }
3233

3234
        public T item() {
3235
            return item;
1✔
3236
        }
3237

3238
        /*
3239
         * Documented, #value
3240
         */
3241
        public List<T> value() {
3242
            return list;
1✔
3243
        }
3244

3245
        public Map<String, Object> map() {
3246
            return map;
1✔
3247
        }
3248

3249
        public List<T> toList() {
3250
            return list;
1✔
3251
        }
3252

3253
        public String toString() {
3254
            return String.valueOf(list);
1✔
3255
        }
3256
    }
3257

3258
    /*
3259
     * Documented, #mixin
3260
     */
3261
    public static void mixin(final String funcName, final UnaryOperator<String> func) {
3262
        FUNCTIONS.put(funcName, func);
1✔
3263
    }
1✔
3264

3265
    public Optional<String> call(final String funcName) {
3266
        if (string.isPresent() && FUNCTIONS.containsKey(funcName)) {
1✔
3267
            return Optional.of(FUNCTIONS.get(funcName).apply(string.get()));
1✔
3268
        }
3269
        return Optional.empty();
1✔
3270
    }
3271

3272
    public static <T extends Comparable<T>> List<T> sort(final Iterable<T> iterable) {
3273
        final List<T> localList = newArrayList(iterable);
1✔
3274
        Collections.sort(localList);
1✔
3275
        return localList;
1✔
3276
    }
3277

3278
    @SuppressWarnings("unchecked")
3279
    public static <T extends Comparable<T>> T[] sort(final T... array) {
3280
        final T[] localArray = array.clone();
1✔
3281
        Arrays.sort(localArray);
1✔
3282
        return localArray;
1✔
3283
    }
3284

3285
    @SuppressWarnings("unchecked")
3286
    public List<Comparable> sort() {
3287
        return sort((Iterable<Comparable>) iterable);
1✔
3288
    }
3289

3290
    /*
3291
     * Documented, #join
3292
     */
3293
    public static <T> String join(final Iterable<T> iterable, final String separator) {
3294
        final StringBuilder sb = new StringBuilder();
1✔
3295
        int index = 0;
1✔
3296
        for (final T item : iterable) {
1✔
3297
            if (index > 0) {
1✔
3298
                sb.append(separator);
1✔
3299
            }
3300
            sb.append(item.toString());
1✔
3301
            index += 1;
1✔
3302
        }
1✔
3303
        return sb.toString();
1✔
3304
    }
3305

3306
    public static <T> String join(final Iterable<T> iterable) {
3307
        return join(iterable, " ");
1✔
3308
    }
3309

3310
    public static <T> String join(final T[] array, final String separator) {
3311
        return join(Arrays.asList(array), separator);
1✔
3312
    }
3313

3314
    public static <T> String join(final T[] array) {
3315
        return join(array, " ");
1✔
3316
    }
3317

3318
    public String join(final String separator) {
3319
        return join(iterable, separator);
1✔
3320
    }
3321

3322
    public String join() {
3323
        return join(iterable);
1✔
3324
    }
3325

3326
    @SuppressWarnings("unchecked")
3327
    public static <T> List<T> push(final List<T> list, final T... values) {
3328
        final List<T> result = newArrayList(list);
1✔
3329
        Collections.addAll(result, values);
1✔
3330
        return result;
1✔
3331
    }
3332

3333
    @SuppressWarnings("unchecked")
3334
    public List<T> push(final T... values) {
3335
        return push((List<T>) getIterable(), values);
1✔
3336
    }
3337

3338
    public static <T> Map.Entry<T, List<T>> pop(final List<T> list) {
3339
        return Map.entry(last(list), initial(list));
1✔
3340
    }
3341

3342
    public Map.Entry<T, List<T>> pop() {
3343
        return pop((List<T>) getIterable());
1✔
3344
    }
3345

3346
    @SuppressWarnings("unchecked")
3347
    public static <T> List<T> unshift(final List<T> list, final T... values) {
3348
        final List<T> result = newArrayList(list);
1✔
3349
        int index = 0;
1✔
3350
        for (T value : values) {
1✔
3351
            result.add(index, value);
1✔
3352
            index += 1;
1✔
3353
        }
3354
        return result;
1✔
3355
    }
3356

3357
    @SuppressWarnings("unchecked")
3358
    public List<T> unshift(final T... values) {
3359
        return unshift((List<T>) getIterable(), values);
1✔
3360
    }
3361

3362
    public static <T> Map.Entry<T, List<T>> shift(final List<T> list) {
3363
        return Map.entry(first(list), rest(list));
1✔
3364
    }
3365

3366
    public Map.Entry<T, List<T>> shift() {
3367
        return shift((List<T>) getIterable());
1✔
3368
    }
3369

3370
    @SuppressWarnings("unchecked")
3371
    public static <T> T[] concat(final T[] first, final T[]... other) {
3372
        int length = 0;
1✔
3373
        for (T[] otherItem : other) {
1✔
3374
            length += otherItem.length;
1✔
3375
        }
3376
        final T[] result = Arrays.copyOf(first, first.length + length);
1✔
3377
        int index = 0;
1✔
3378
        for (T[] otherItem : other) {
1✔
3379
            System.arraycopy(otherItem, 0, result, first.length + index, otherItem.length);
1✔
3380
            index += otherItem.length;
1✔
3381
        }
3382
        return result;
1✔
3383
    }
3384

3385
    /*
3386
     * Documented, #concat
3387
     */
3388
    @SuppressWarnings("unchecked")
3389
    public static <T> List<T> concat(final Iterable<T> first, final Iterable<T>... other) {
3390
        List<T> list = newArrayList(first);
1✔
3391
        for (Iterable<T> iter : other) {
1✔
3392
            list.addAll(newArrayList(iter));
1✔
3393
        }
3394
        return list;
1✔
3395
    }
3396

3397
    @SuppressWarnings("unchecked")
3398
    public List<T> concatWith(final Iterable<T>... other) {
3399
        return concat(iterable, other);
1✔
3400
    }
3401

3402
    /*
3403
     * Documented, #slice
3404
     */
3405
    public static <T> List<T> slice(final Iterable<T> iterable, final int start) {
3406
        final List<T> result;
3407
        if (start >= 0) {
1✔
3408
            result = newArrayList(iterable).subList(start, size(iterable));
1✔
3409
        } else {
3410
            result = newArrayList(iterable).subList(size(iterable) + start, size(iterable));
1✔
3411
        }
3412
        return result;
1✔
3413
    }
3414

3415
    public static <T> T[] slice(final T[] array, final int start) {
3416
        final T[] result;
3417
        if (start >= 0) {
1✔
3418
            result = Arrays.copyOfRange(array, start, array.length);
1✔
3419
        } else {
3420
            result = Arrays.copyOfRange(array, array.length + start, array.length);
1✔
3421
        }
3422
        return result;
1✔
3423
    }
3424

3425
    public List<T> slice(final int start) {
3426
        return slice(iterable, start);
1✔
3427
    }
3428

3429
    public static <T> List<T> slice(final Iterable<T> iterable, final int start, final int end) {
3430
        final List<T> result;
3431
        if (start >= 0) {
1✔
3432
            if (end > 0) {
1✔
3433
                result = newArrayList(iterable).subList(start, end);
1✔
3434
            } else {
3435
                result = newArrayList(iterable).subList(start, size(iterable) + end);
1✔
3436
            }
3437
        } else {
3438
            if (end > 0) {
1✔
3439
                result = newArrayList(iterable).subList(size(iterable) + start, end);
1✔
3440
            } else {
3441
                result =
1✔
3442
                        newArrayList(iterable)
1✔
3443
                                .subList(size(iterable) + start, size(iterable) + end);
1✔
3444
            }
3445
        }
3446
        return result;
1✔
3447
    }
3448

3449
    public static <T> T[] slice(final T[] array, final int start, final int end) {
3450
        final T[] result;
3451
        if (start >= 0) {
1✔
3452
            if (end > 0) {
1✔
3453
                result = Arrays.copyOfRange(array, start, end);
1✔
3454
            } else {
3455
                result = Arrays.copyOfRange(array, start, array.length + end);
1✔
3456
            }
3457
        } else {
3458
            if (end > 0) {
1✔
3459
                result = Arrays.copyOfRange(array, array.length + start, end);
1✔
3460
            } else {
3461
                result = Arrays.copyOfRange(array, array.length + start, array.length + end);
1✔
3462
            }
3463
        }
3464
        return result;
1✔
3465
    }
3466

3467
    public List<T> slice(final int start, final int end) {
3468
        return slice(iterable, start, end);
1✔
3469
    }
3470

3471
    public static <T> List<List<T>> splitAt(final Iterable<T> iterable, final int position) {
3472
        List<List<T>> result = newArrayList();
1✔
3473
        int size = size(iterable);
1✔
3474
        final int index;
3475
        if (position < 0) {
1✔
3476
            index = 0;
1✔
3477
        } else {
3478
            index = position > size ? size : position;
1✔
3479
        }
3480
        result.add(newArrayList(iterable).subList(0, index));
1✔
3481
        result.add(newArrayList(iterable).subList(index, size));
1✔
3482
        return result;
1✔
3483
    }
3484

3485
    public static <T> List<List<T>> splitAt(final T[] array, final int position) {
3486
        return splitAt(Arrays.asList(array), position);
1✔
3487
    }
3488

3489
    public List<List<T>> splitAt(final int position) {
3490
        return splitAt(iterable, position);
1✔
3491
    }
3492

3493
    public static <T> List<T> takeSkipping(final Iterable<T> iterable, final int stepSize) {
3494
        List<T> result = newArrayList();
1✔
3495
        if (stepSize <= 0) {
1✔
3496
            return result;
1✔
3497
        }
3498
        int size = size(iterable);
1✔
3499
        if (stepSize > size) {
1✔
3500
            result.add(first(iterable));
1✔
3501
            return result;
1✔
3502
        }
3503
        int i = 0;
1✔
3504
        for (T element : iterable) {
1✔
3505
            if (i++ % stepSize == 0) {
1✔
3506
                result.add(element);
1✔
3507
            }
3508
        }
1✔
3509
        return result;
1✔
3510
    }
3511

3512
    public static <T> List<T> takeSkipping(final T[] array, final int stepSize) {
3513
        return takeSkipping(Arrays.asList(array), stepSize);
1✔
3514
    }
3515

3516
    public List<T> takeSkipping(final int stepSize) {
3517
        return takeSkipping(iterable, stepSize);
1✔
3518
    }
3519

3520
    /*
3521
     * Documented, #reverse
3522
     */
3523
    public static <T> List<T> reverse(final Iterable<T> iterable) {
3524
        final List<T> result = newArrayList(iterable);
1✔
3525
        Collections.reverse(result);
1✔
3526
        return result;
1✔
3527
    }
3528

3529
    @SuppressWarnings("unchecked")
3530
    public static <T> T[] reverse(final T... array) {
3531
        T temp;
3532
        final T[] newArray = array.clone();
1✔
3533
        for (int index = 0; index < array.length / 2; index += 1) {
1✔
3534
            temp = newArray[index];
1✔
3535
            newArray[index] = newArray[array.length - 1 - index];
1✔
3536
            newArray[array.length - 1 - index] = temp;
1✔
3537
        }
3538
        return newArray;
1✔
3539
    }
3540

3541
    public static List<Integer> reverse(final int[] array) {
3542
        final List<Integer> result = newIntegerList(array);
1✔
3543
        Collections.reverse(result);
1✔
3544
        return result;
1✔
3545
    }
3546

3547
    public List<T> reverse() {
3548
        return reverse(iterable);
1✔
3549
    }
3550

3551
    public Iterable<T> getIterable() {
3552
        return iterable;
1✔
3553
    }
3554

3555
    public Iterable<T> value() {
3556
        return iterable;
1✔
3557
    }
3558

3559
    public Optional<String> getString() {
3560
        return string;
1✔
3561
    }
3562

3563
    public static <T> java.util.concurrent.ScheduledFuture<T> setTimeout(
3564
            final Supplier<T> function, final int delayMilliseconds) {
3565
        return delay(function, delayMilliseconds);
1✔
3566
    }
3567

3568
    public static void clearTimeout(java.util.concurrent.ScheduledFuture<?> scheduledFuture) {
3569
        if (scheduledFuture != null) {
1✔
3570
            scheduledFuture.cancel(true);
1✔
3571
        }
3572
    }
1✔
3573

3574
    public static <T> java.util.concurrent.ScheduledFuture setInterval(
3575
            final Supplier<T> function, final int delayMilliseconds) {
3576
        final java.util.concurrent.ScheduledExecutorService scheduler =
3577
                java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
1✔
3578
        return scheduler.scheduleAtFixedRate(
1✔
3579
                function::get,
1✔
3580
                delayMilliseconds,
3581
                delayMilliseconds,
3582
                java.util.concurrent.TimeUnit.MILLISECONDS);
3583
    }
3584

3585
    public static void clearInterval(java.util.concurrent.ScheduledFuture scheduledFuture) {
3586
        clearTimeout(scheduledFuture);
1✔
3587
    }
1✔
3588

3589
    public static <T> List<T> copyOf(final Iterable<T> iterable) {
3590
        return newArrayList(iterable);
1✔
3591
    }
3592

3593
    public List<T> copyOf() {
3594
        return newArrayList(value());
1✔
3595
    }
3596

3597
    public static <T> List<T> copyOfRange(
3598
            final Iterable<T> iterable, final int start, final int end) {
3599
        return slice(iterable, start, end);
1✔
3600
    }
3601

3602
    public List<T> copyOfRange(final int start, final int end) {
3603
        return slice(value(), start, end);
1✔
3604
    }
3605

3606
    public static <T> T elementAt(final List<T> list, final int index) {
3607
        return list.get(index);
1✔
3608
    }
3609

3610
    public T elementAt(final int index) {
3611
        return elementAt((List<T>) value(), index);
1✔
3612
    }
3613

3614
    public static <T> T get(final List<T> list, final int index) {
3615
        return elementAt(list, index);
1✔
3616
    }
3617

3618
    public T get(final int index) {
3619
        return elementAt((List<T>) value(), index);
1✔
3620
    }
3621

3622
    public static <T> Map.Entry<T, List<T>> set(
3623
            final List<T> list, final int index, final T value) {
3624
        final List<T> newList = newArrayList(list);
1✔
3625
        return Map.entry(newList.set(index, value), newList);
1✔
3626
    }
3627

3628
    public Map.Entry<T, List<T>> set(final int index, final T value) {
3629
        return set((List<T>) value(), index, value);
1✔
3630
    }
3631

3632
    public static <T> T elementAtOrElse(final List<T> list, final int index, T defaultValue) {
3633
        try {
3634
            return list.get(index);
1✔
3635
        } catch (IndexOutOfBoundsException ex) {
1✔
3636
            return defaultValue;
1✔
3637
        }
3638
    }
3639

3640
    public T elementAtOrElse(final int index, T defaultValue) {
3641
        return elementAtOrElse((List<T>) value(), index, defaultValue);
1✔
3642
    }
3643

3644
    public static <T> T elementAtOrNull(final List<T> list, final int index) {
3645
        try {
3646
            return list.get(index);
1✔
3647
        } catch (IndexOutOfBoundsException ex) {
1✔
3648
            return null;
1✔
3649
        }
3650
    }
3651

3652
    public T elementAtOrNull(final int index) {
3653
        return elementAtOrNull((List<T>) value(), index);
1✔
3654
    }
3655

3656
    public static <T> int lastIndex(final Iterable<T> iterable) {
3657
        return size(iterable) - 1;
1✔
3658
    }
3659

3660
    public static <T> int lastIndex(final T[] array) {
3661
        return array.length - 1;
1✔
3662
    }
3663

3664
    public static int lastIndex(final int[] array) {
3665
        return array.length - 1;
1✔
3666
    }
3667

3668
    public static <T> T checkNotNull(T reference) {
3669
        if (reference == null) {
1✔
3670
            throw new NullPointerException();
1✔
3671
        }
3672
        return reference;
1✔
3673
    }
3674

3675
    public static <T> List<T> checkNotNullElements(List<T> references) {
3676
        if (references == null) {
1✔
3677
            throw new NullPointerException();
1✔
3678
        }
3679
        for (T reference : references) {
1✔
3680
            checkNotNull(reference);
1✔
3681
        }
1✔
3682
        return references;
1✔
3683
    }
3684

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

3692
    public static boolean nonNull(Object obj) {
3693
        return obj != null;
1✔
3694
    }
3695

3696
    public static <T> T defaultTo(T value, T defaultValue) {
3697
        if (value == null) {
1✔
3698
            return defaultValue;
1✔
3699
        }
3700
        return value;
1✔
3701
    }
3702

3703
    protected static <T> List<T> newArrayList() {
3704
        return new ArrayList<>();
1✔
3705
    }
3706

3707
    protected static <T> List<T> newArrayList(final Iterable<T> iterable) {
3708
        final List<T> result;
3709
        if (iterable instanceof Collection) {
1✔
3710
            result = new ArrayList<>((Collection<T>) iterable);
1✔
3711
        } else {
3712
            result = new ArrayList<>();
1✔
3713
            for (final T item : iterable) {
1✔
3714
                result.add(item);
1✔
3715
            }
1✔
3716
        }
3717
        return result;
1✔
3718
    }
3719

3720
    protected static <T> List<T> newArrayList(final T object) {
3721
        final List<T> result = new ArrayList<>();
1✔
3722
        result.add(object);
1✔
3723
        return result;
1✔
3724
    }
3725

3726
    protected static <T> List<T> newArrayList(final Iterable<T> iterable, final int size) {
3727
        final List<T> result = new ArrayList<>();
1✔
3728
        for (int index = 0; iterable.iterator().hasNext() && index < size; index += 1) {
1✔
3729
            result.add(iterable.iterator().next());
1✔
3730
        }
3731
        return result;
1✔
3732
    }
3733

3734
    protected static List<Integer> newIntegerList(int... array) {
3735
        final List<Integer> result = new ArrayList<>(array.length);
1✔
3736
        for (final int item : array) {
1✔
3737
            result.add(item);
1✔
3738
        }
3739
        return result;
1✔
3740
    }
3741

3742
    protected static <T> List<T> newArrayListWithExpectedSize(int size) {
3743
        return new ArrayList<>((int) (CAPACITY_SIZE_5 + size + (size / 10)));
1✔
3744
    }
3745

3746
    protected static <T> Set<T> newLinkedHashSet() {
3747
        return new LinkedHashSet<>();
1✔
3748
    }
3749

3750
    protected static <T> Set<T> newLinkedHashSet(Iterable<T> iterable) {
3751
        final Set<T> result = new LinkedHashSet<>();
1✔
3752
        for (final T item : iterable) {
1✔
3753
            result.add(item);
1✔
3754
        }
1✔
3755
        return result;
1✔
3756
    }
3757

3758
    protected static <T> Set<T> newLinkedHashSetWithExpectedSize(int size) {
3759
        return new LinkedHashSet<>((int) Math.max(size * CAPACITY_COEFF_2, CAPACITY_SIZE_16));
1✔
3760
    }
3761

3762
    protected static <K, E> Map<K, E> newLinkedHashMap() {
3763
        return new LinkedHashMap<>();
1✔
3764
    }
3765

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

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

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

3819
    public static interface Function3<F1, F2, F3, T> {
3820
        T apply(F1 arg1, F2 arg2, F3 arg3);
3821
    }
3822

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

3826
        public abstract T calc(final F n);
3827

3828
        public T apply(final F key) {
3829
            cache.putIfAbsent(key, calc(key));
1✔
3830
            return cache.get(key);
1✔
3831
        }
3832
    }
3833

3834
    public static interface PredicateIndexed<T> {
3835
        boolean test(int index, T arg);
3836
    }
3837

3838
    public static interface Template<T> extends Function<T, String> {
3839
        List<String> check(T arg);
3840
    }
3841
}
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

© 2026 Coveralls, Inc