OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils;
15
 
19 ilm 16
import org.openconcerto.utils.cc.IClosure;
17
import org.openconcerto.utils.cc.IPredicate;
17 ilm 18
import org.openconcerto.utils.cc.ITransformer;
180 ilm 19
import org.openconcerto.utils.cc.ITransformerExn;
65 ilm 20
import org.openconcerto.utils.cc.IdentityHashSet;
21
import org.openconcerto.utils.cc.IdentitySet;
174 ilm 22
import org.openconcerto.utils.cc.LinkedIdentitySet;
132 ilm 23
import org.openconcerto.utils.cc.Transformer;
17 ilm 24
 
73 ilm 25
import java.io.Serializable;
26
import java.util.AbstractSet;
17 ilm 27
import java.util.ArrayList;
28
import java.util.Arrays;
29
import java.util.Collection;
30
import java.util.Collections;
31
import java.util.HashMap;
32
import java.util.HashSet;
180 ilm 33
import java.util.IdentityHashMap;
17 ilm 34
import java.util.Iterator;
35
import java.util.LinkedHashMap;
180 ilm 36
import java.util.LinkedHashSet;
73 ilm 37
import java.util.LinkedList;
17 ilm 38
import java.util.List;
73 ilm 39
import java.util.ListIterator;
17 ilm 40
import java.util.Map;
132 ilm 41
import java.util.Map.Entry;
73 ilm 42
import java.util.NoSuchElementException;
17 ilm 43
import java.util.RandomAccess;
44
import java.util.Set;
180 ilm 45
import java.util.SortedMap;
46
import java.util.SortedSet;
47
import java.util.TreeMap;
48
import java.util.TreeSet;
49
import java.util.function.Function;
17 ilm 50
import java.util.regex.Pattern;
51
 
52
/**
53
 * Une classe regroupant des méthodes utilitaires pour les collections.
54
 *
55
 * @author ILM Informatique 30 sept. 2004
56
 */
67 ilm 57
public class CollectionUtils {
17 ilm 58
 
59
    /**
60
     * Concatene une collection. Cette méthode va appliquer un transformation sur chaque élément
61
     * avant d'appeler toString(). join([-1, 3, 0], " ,", doubleTransformer) == "-2, 6, 0"
62
     *
63
     * @param <E> type of items
64
     * @param c la collection a concaténer.
65
     * @param sep le séparateur entre chaque élément.
66
     * @param tf la transformation à appliquer à chaque élément.
67
     * @return la chaine composée de chacun des éléments séparés par <code>sep</code>.
68
     */
69
    static public final <E> String join(final Collection<E> c, final String sep, final ITransformer<? super E, ?> tf) {
19 ilm 70
        final int size = c.size();
71
        if (size == 0)
17 ilm 72
            return "";
73
 
19 ilm 74
        final StringBuffer res = new StringBuffer(size * 4);
17 ilm 75
        if (c instanceof RandomAccess && c instanceof List) {
76
            final List<E> list = (List<E>) c;
19 ilm 77
            for (int i = 0; i < size; i++) {
17 ilm 78
                res.append(tf.transformChecked(list.get(i)));
19 ilm 79
                if (i < size - 1)
80
                    res.append(sep);
17 ilm 81
            }
82
        } else {
83
            final Iterator<E> iter = c.iterator();
84
            while (iter.hasNext()) {
85
                final E elem = iter.next();
86
                res.append(tf.transformChecked(elem));
87
                if (iter.hasNext())
88
                    res.append(sep);
89
            }
90
        }
91
        return res.toString();
92
    }
93
 
94
    /**
95
     * Concatene une collection en appelant simplement toString() sur chaque élément.
96
     *
97
     * @param <T> type of collection
98
     * @param c la collection a concaténer.
99
     * @param sep le séparateur entre chaque élément.
100
     * @return la chaine composée de chacun des éléments séparés par <code>sep</code>.
101
     * @see #join(Collection, String, ITransformer)
102
     */
103
    static public <T> String join(Collection<T> c, String sep) {
149 ilm 104
        return join(c, sep, org.openconcerto.utils.cc.Transformer.<T> nopTransformer());
17 ilm 105
    }
106
 
67 ilm 107
    static public <T, U, C extends Collection<? super U>> C transform(final Collection<T> c, final ITransformer<? super T, U> transf, final C res) {
108
        return transformAndFilter(c, transf, IPredicate.truePredicate(), res);
109
    }
110
 
111
    static public <T, U, C extends Collection<? super U>> C transformAndFilter(final Collection<T> c, final ITransformer<? super T, U> transf, final IPredicate<? super U> filterAfter, final C res) {
112
        return filterTransformAndFilter(c, IPredicate.truePredicate(), transf, filterAfter, res);
113
    }
114
 
115
    static public <T, U, C extends Collection<? super U>> C filterAndTransform(final Collection<T> c, final IPredicate<? super T> filterBefore, final ITransformer<? super T, U> transf, final C res) {
116
        return filterTransformAndFilter(c, filterBefore, transf, IPredicate.truePredicate(), res);
117
    }
118
 
119
    static public <T, U, C extends Collection<? super U>> C filterTransformAndFilter(final Collection<T> c, final IPredicate<? super T> filterBefore, final ITransformer<? super T, U> transf,
120
            final IPredicate<? super U> filterAfter, final C res) {
121
        iterate(c, filterBefore, new IClosure<T>() {
19 ilm 122
            @Override
123
            public void executeChecked(T input) {
124
                final U item = transf.transformChecked(input);
67 ilm 125
                if (filterAfter.evaluateChecked(item))
19 ilm 126
                    res.add(item);
127
            }
128
        });
129
        return res;
130
    }
17 ilm 131
 
19 ilm 132
    static public <T> void iterate(final Collection<T> c, final IClosure<T> cl) {
67 ilm 133
        iterate(c, IPredicate.truePredicate(), cl);
134
    }
135
 
136
    static public <T> void iterate(final Collection<T> c, final IPredicate<? super T> filterBefore, final IClosure<T> cl) {
19 ilm 137
        if (c instanceof RandomAccess && c instanceof List) {
138
            final List<T> list = (List<T>) c;
139
            final int size = c.size();
140
            for (int i = 0; i < size; i++) {
67 ilm 141
                final T item = list.get(i);
142
                if (filterBefore.evaluateChecked(item))
143
                    cl.executeChecked(item);
19 ilm 144
            }
145
        } else {
146
            final Iterator<T> iter = c.iterator();
147
            while (iter.hasNext()) {
67 ilm 148
                final T item = iter.next();
149
                if (filterBefore.evaluateChecked(item))
150
                    cl.executeChecked(item);
19 ilm 151
            }
152
        }
153
    }
154
 
17 ilm 155
    private static final Pattern COMMA = Pattern.compile("\\p{Space}*,\\p{Space}*");
156
 
157
    static public List<String> split(String s) {
158
        return split(s, COMMA);
159
    }
160
 
161
    static public List<String> split(String s, String sep) {
162
        return split(s, Pattern.compile(sep));
163
    }
164
 
165
    /**
166
     * Split a string into a list based on a pattern.
167
     *
168
     * @param s the string to split.
169
     * @param pattern the pattern where to cut the string.
170
     * @return the splitted string, empty list if <code>s</code> is "".
171
     */
172
    static public List<String> split(String s, Pattern pattern) {
149 ilm 173
        return s.length() == 0 ? Collections.<String> emptyList() : Arrays.asList(pattern.split(s));
17 ilm 174
    }
175
 
176
    /**
177
     * Return an index between <code>0</code> and <code>l.size()</code> inclusive. If <code>i</code>
93 ilm 178
     * is negative, it is added to <code>l.size()</code> (i.e. -1 is the index of the last item and
179
     * -size is the first) :
17 ilm 180
     *
181
     * <pre>
182
     *    a  b  c  a  b  c
183
     *   -3 -2 -1  0  1  2  3
184
     * </pre>
185
     *
93 ilm 186
     * @param l the list, e.g. a list of 3 items.
187
     * @param i the virtual index, e.g. -1.
188
     * @return the real index, e.g. 2.
189
     * @throws IndexOutOfBoundsException if not <code>0 &le; abs(i) &le; l.size()</code>
17 ilm 190
     */
93 ilm 191
    static public int getValidIndex(final List<?> l, final int i) throws IndexOutOfBoundsException {
192
        return getValidIndex(l, i, true);
61 ilm 193
    }
194
 
93 ilm 195
    /**
196
     * Return an index between <code>0</code> and <code>l.size()</code> inclusive. If <code>i</code>
197
     * is negative, it is added to <code>l.size()</code> (bounded to 0 if <code>strict</code> is
198
     * <code>false</code>), i.e. for a list of 3 items, -1 is the index of the last item ; -3 and -4
199
     * are both the first. If <code>i</code> is greater than <code>l.size()</code> then
200
     * <code>l.size()</code> is returned if not <code>strict</code>.
201
     *
202
     * @param l the list, e.g. a list of 3 items.
203
     * @param i the virtual index, e.g. -1.
204
     * @param strict if <code>true</code> <code>abs(i)</code> must be between <code>0</code> and
205
     *        <code>l.size()</code>, else values are bounded between <code>0</code> and
206
     *        <code>l.size()</code>.
207
     * @return the real index between <code>0</code> and <code>l.size()</code>, e.g. 2.
208
     * @throws IndexOutOfBoundsException if <code>strict</code> is <code>true</code> and not
209
     *         <code>0 &le; abs(i) &le; l.size()</code>
210
     */
211
    static public int getValidIndex(final List<?> l, final int i, final boolean strict) throws IndexOutOfBoundsException {
61 ilm 212
        final int size = l.size();
213
        if (i > size) {
214
            if (strict)
215
                throw new IndexOutOfBoundsException("Too high : " + i + " > " + size);
216
            return size;
217
        } else if (i < -size) {
218
            if (strict)
219
                throw new IndexOutOfBoundsException("Too low : " + i + " < " + -size);
220
            return 0;
17 ilm 221
        } else if (i >= 0) {
222
            return i;
61 ilm 223
        } else {
224
            return size + i;
225
        }
17 ilm 226
    }
227
 
228
    /**
93 ilm 229
     * Deletes a slice of a list. Pass indexes to {@link #getValidIndex(List, int, boolean)} to
230
     * allow delete(l, 0, -1) to clear l or delete(l, -2, -2) to remove the penultimate item.
17 ilm 231
     *
232
     * @param l the list to delete from.
233
     * @param from the first index to be removed (inclusive).
234
     * @param to the last index to be removed (inclusive).
235
     */
236
    static public void delete(List<?> l, int from, int to) {
237
        if (!l.isEmpty())
93 ilm 238
            l.subList(getValidIndex(l, from, false), getValidIndex(l, to, false) + 1).clear();
17 ilm 239
    }
240
 
241
    /**
242
     * Deletes the tail of a list. The resulting list will have a size of <code>from</code>.
243
     *
244
     * @param l the list to delete from.
245
     * @param from the first index to be removed (inclusive).
246
     */
247
    static public void delete(List<?> l, int from) {
248
        delete(l, from, -1);
249
    }
250
 
67 ilm 251
    public static <T> boolean exists(Collection<T> collection, IPredicate<? super T> predicate) {
180 ilm 252
        return collection.stream().anyMatch(predicate::evaluateChecked);
67 ilm 253
    }
254
 
17 ilm 255
    /**
256
     * Convertit une map en 2 listes, une pour les clefs, une pour les valeurs.
257
     *
258
     * @param map la Map à convertir.
259
     * @return un tuple de 2 List, en 0 les clefs, en 1 les valeurs.
260
     * @param <K> type of key
261
     * @param <V> type of value
262
     */
263
    static public <K, V> Tuple2<List<K>, List<V>> mapToLists(Map<K, V> map) {
264
        final List<K> keys = new ArrayList<K>(map.size());
265
        final List<V> vals = new ArrayList<V>(map.size());
266
        for (final Map.Entry<K, V> e : map.entrySet()) {
267
            keys.add(e.getKey());
268
            vals.add(e.getValue());
269
        }
270
 
271
        return Tuple2.create(keys, vals);
272
    }
273
 
274
    /**
275
     * Add entries from <code>toAdd</code> into <code>map</code> only if the key is not already
276
     * present.
277
     *
278
     * @param <K> type of keys.
279
     * @param <V> type of values.
280
     * @param map the map to fill.
281
     * @param toAdd the entries to add.
282
     * @return <code>map</code>.
283
     */
284
    static public <K, V> Map<K, V> addIfNotPresent(Map<K, V> map, Map<? extends K, ? extends V> toAdd) {
285
        for (final Map.Entry<? extends K, ? extends V> e : toAdd.entrySet()) {
286
            if (!map.containsKey(e.getKey()))
287
                map.put(e.getKey(), e.getValue());
288
        }
289
        return map;
290
    }
291
 
180 ilm 292
    // compared to computeIfAbsent() :
293
    // 1. allow exceptions
294
    // 2. allow nulls
295
    static public <K, V, X extends Exception> V computeIfAbsent(final Map<K, V> map, final K key, final ITransformerExn<K, V, X> function, final boolean allowNullValue) throws X {
296
        V res = map.get(key);
297
        final boolean contains;
298
        if (allowNullValue) {
299
            contains = res != null || map.containsKey(key);
300
        } else {
301
            contains = res != null;
302
        }
303
        if (!contains) {
304
            res = function.transformChecked(key);
305
            if (res == null && !allowNullValue)
306
                throw new IllegalStateException("Null value computed for key '" + key + "'");
307
            map.put(key, res);
308
        }
309
        assert allowNullValue || res != null;
310
        return res;
311
    }
312
 
17 ilm 313
    /**
314
     * Compute the index that have changed (added or removed) between 2 lists. One of the lists MUST
315
     * be a sublist of the other, ie the to go from one to the other we just add or remove items but
316
     * we don't do both.
317
     *
318
     * @param oldList the first list.
319
     * @param newList the second list.
320
     * @return a list of Integer.
321
     * @param <E> type of item
322
     * @throws IllegalStateException if one list is not a sublist of the other.
323
     */
324
    static public <E> List<Integer> getIndexesChanged(List<E> oldList, List<E> newList) {
325
        final List<E> longer;
326
        final List<E> shorter;
327
        if (newList.size() > oldList.size()) {
328
            longer = new ArrayList<E>(newList);
329
            shorter = new ArrayList<E>(oldList);
330
        } else {
331
            longer = new ArrayList<E>(oldList);
332
            shorter = new ArrayList<E>(newList);
333
        }
334
 
335
        final List<Integer> res = new ArrayList<Integer>();
336
        int offset = 0;
337
        while (shorter.size() > 0) {
338
            if (longer.size() < shorter.size())
339
                throw new IllegalStateException(shorter + " is not a sublist of " + longer);
340
            // compare nulls
341
            if (CompareUtils.equals(shorter.get(0), longer.get(0))) {
342
                shorter.remove(0);
343
                longer.remove(0);
344
            } else {
345
                longer.remove(0);
346
                res.add(offset);
347
            }
348
            offset++;
349
        }
350
 
351
        for (int i = 0; i < longer.size(); i++) {
352
            res.add(i + offset);
353
        }
354
 
355
        return res;
356
    }
357
 
358
    /**
359
     * Aggregate a list of ints into a list of intervals. Eg aggregate([-1,0,1,2,5]) returns
360
     * [[-1,2], [5,5]].
361
     *
362
     * @param ints a list of Integer strictly increasing.
363
     * @return a list of int[2].
364
     */
365
    static public List<int[]> aggregate(Collection<? extends Number> ints) {
366
        final List<int[]> res = new ArrayList<int[]>();
367
        int[] currentInterval = null;
368
        for (final Number n : ints) {
369
            final int index = n.intValue();
370
            if (currentInterval == null || index != currentInterval[1] + 1) {
371
                currentInterval = new int[2];
372
                currentInterval[0] = index;
373
                currentInterval[1] = currentInterval[0];
374
                res.add(currentInterval);
375
            } else {
376
                currentInterval[1] = index;
377
            }
378
        }
379
        return res;
380
    }
381
 
382
    /**
383
     * Test whether col2 is contained in col1.
384
     *
385
     * @param <T> type of collection
386
     * @param col1 the first collection
387
     * @param col2 the second collection
388
     * @return <code>null</code> if col1 contains all of col2, else return the extra items that col2
389
     *         have.
390
     */
391
    static public <T> Set<T> contains(final Set<T> col1, final Set<T> col2) {
392
        if (col1.containsAll(col2))
393
            return null;
394
        else {
395
            final Set<T> names = new HashSet<T>(col2);
396
            names.removeAll(col1);
397
            return names;
398
        }
399
    }
400
 
67 ilm 401
    static public <C extends Collection<?>> boolean containsAny(final C coll1, final C coll2) {
142 ilm 402
        return !Collections.disjoint(coll1, coll2);
67 ilm 403
    }
404
 
180 ilm 405
    static public final boolean identityContains(final Collection<?> coll, final Object item) {
406
        for (final Object v : coll) {
93 ilm 407
            if (item == v)
408
                return true;
409
        }
410
        return false;
411
    }
412
 
180 ilm 413
    static public final boolean identityEquals(final List<?> coll1, final List<?> coll2) {
414
        if (coll1 == coll2)
415
            return true;
416
        final int size = coll1.size();
417
        if (size != coll2.size())
418
            return false;
419
        if (size == 0)
420
            return true;
421
 
422
        final Iterator<?> iter1 = coll1.iterator();
423
        final Iterator<?> iter2 = coll2.iterator();
424
        while (iter1.hasNext()) {
425
            final Object elem1 = iter1.next();
426
            final Object elem2 = iter2.next();
427
            if (elem1 != elem2)
428
                return false;
429
        }
430
        assert !iter2.hasNext();
431
        return true;
432
    }
433
 
17 ilm 434
    /**
435
     * Convert an array to a list of a different type.
436
     *
437
     * @param <U> type of array
438
     * @param <T> type of list
439
     * @param array the array to convert, eg new Object[]{"a", "b"}.
440
     * @param clazz the class of the list items, eg String.class.
441
     * @return all items of <code>array</code> into a list, eg ["a", "b"].
442
     * @throws ClassCastException if some item of <code>array</code> is not a <code>T</code>.
443
     */
444
    static public <U, T extends U> List<T> castToList(U[] array, Class<T> clazz) throws ClassCastException {
445
        final List<T> res = new ArrayList<T>(array.length);
446
        for (final U item : array) {
447
            res.add(clazz.cast(item));
448
        }
449
        return res;
450
    }
451
 
452
    /**
142 ilm 453
     * Cast list
454
     *
455
     * @param <E> type of result list
456
     * @param list the list to convert
457
     * @param c the class of the result list
458
     * @return a new ArrayList create from <code>list</code> or null if <code>list</code> is null
459
     * @throws ClassCastException if some item of <code>list</code> is not a <code>E</code>.
460
     */
461
    public static <E> List<E> castList(final List<?> list, Class<E> c) throws ClassCastException {
462
        if (list == null) {
463
            return null;
464
        }
465
 
177 ilm 466
        final int size = list.size();
467
        final List<E> result = new ArrayList<E>(size);
142 ilm 468
        for (int i = 0; i < list.size(); i++) {
469
            result.add(c.cast(list.get(i)));
470
        }
471
        return result;
472
    }
473
 
474
    /**
475
     * Cast Map
476
     *
477
     * @param <E> type of key
478
     * @param <F> type of value
479
     * @param map the map to convert
480
     * @param cKey the class of key
481
     * @param cValue the class of value
482
     * @return a new HashMap create from the <code>map</code> or null if <code>map</code> is null
483
     * @throws ClassCastException if some item of <code>map</code> have a key which the type is not
484
     *         a <code>E</code> or a value which the type is not a <code>F</code>.
485
     */
486
    public static <E, F> Map<E, F> castMap(final Map<?, ?> map, Class<E> cKey, Class<F> cValue) throws ClassCastException {
487
        if (map == null) {
488
            return null;
489
        }
490
 
491
        final Map<E, F> result = new HashMap<E, F>();
492
        for (final Entry<?, ?> mapEntry : map.entrySet()) {
493
            final E key;
494
            try {
495
                key = cKey.cast(mapEntry.getKey());
496
            } catch (final ClassCastException ex) {
497
                throw new ClassCastException("Key " + mapEntry.getKey().toString() + " is not valid: " + ex.getMessage());
498
            }
499
            final F value;
500
            try {
501
                value = cValue.cast(mapEntry.getValue());
502
            } catch (final ClassCastException ex) {
503
                throw new ClassCastException("Value " + mapEntry.getKey().toString() + " is not valid: " + ex.getMessage());
504
            }
505
            result.put(key, value);
506
        }
507
        return result;
508
    }
509
 
510
    /**
17 ilm 511
     * The number of equals item between a and b, starting from the end.
512
     *
513
     * @param <T> type of items.
514
     * @param a the first list, eg [a, b, c].
515
     * @param b the second list, eg [a, null, z, c].
516
     * @return the number of common items, eg 1.
517
     */
518
    public static <T> int equalsFromEnd(final List<T> a, final List<T> b) {
519
        return equals(a, b, true, null);
520
    }
521
 
522
    public static <T> int equalsFromStart(final List<T> a, final List<T> b) {
523
        return equals(a, b, false, null);
524
    }
525
 
526
    /**
527
     * The number of equals item between a and b, starting from the choosen end.
528
     *
529
     * @param <A> type of the first list.
530
     * @param <B> type of the second list.
531
     * @param a the first list, eg [a, b, c].
532
     * @param b the second list, eg [a, null, z, c].
533
     * @param fromEnd whether search from the start or the end, <code>true</code>.
534
     * @param transf how items of <code>a</code> should be transformed before being compared, can be
535
     *        <code>null</code>.
536
     * @return the number of common items, eg 1.
537
     */
538
    public final static <A, B> int equals(final List<A> a, final List<B> b, boolean fromEnd, ITransformer<A, B> transf) {
539
        final int sizeA = a.size();
540
        final int sizeB = b.size();
541
        final int lastI = Math.min(sizeA, sizeB);
542
        for (int i = 0; i < lastI; i++) {
543
            final A itemA = a.get(fromEnd ? sizeA - 1 - i : i);
544
            final B itemB = b.get(fromEnd ? sizeB - 1 - i : i);
545
            if (!CompareUtils.equals(transf == null ? itemA : transf.transformChecked(itemA), itemB))
546
                return i;
547
        }
548
        return lastI;
549
    }
550
 
83 ilm 551
    public final static <T> int getEqualsCount(final Iterator<? extends T> a, final Iterator<? extends T> b) {
552
        return getEqualsCount(a, b, null);
553
    }
554
 
555
    public final static <A, B> int getEqualsCount(final Iterator<A> a, final Iterator<B> b, final ITransformer<A, B> transf) {
556
        int res = 0;
557
        while (a.hasNext() && b.hasNext()) {
558
            final A itemA = a.next();
559
            final B itemB = b.next();
560
            if (!CompareUtils.equals(transf == null ? itemA : transf.transformChecked(itemA), itemB))
561
                break;
562
            res++;
563
        }
564
        return res;
565
    }
566
 
67 ilm 567
    public static <T> Collection<T> select(final Collection<T> a, final IPredicate<? super T> pred) {
568
        return select(a, pred, new ArrayList<T>());
65 ilm 569
    }
570
 
67 ilm 571
    public static <T, C extends Collection<? super T>> C select(final Collection<T> a, final IPredicate<? super T> pred, final C b) {
65 ilm 572
        for (final T item : a)
573
            if (pred.evaluateChecked(item))
574
                b.add(item);
575
        return b;
576
    }
577
 
17 ilm 578
    // avoid name collision causing eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=319603
579
    @SuppressWarnings("unchecked")
580
    public static <T> Collection<T> intersection(final Collection<T> a, final Collection<T> b) {
581
        return org.apache.commons.collections.CollectionUtils.intersection(a, b);
582
    }
583
 
584
    /**
585
     * Compute the intersection of a and b. <code>null</code>s are ignored : x ∩ null = x.
586
     *
587
     * @param <T> type of collection.
588
     * @param a the first set, can be <code>null</code>.
589
     * @param b the second set, can be <code>null</code>.
590
     * @return the intersection.
591
     */
592
    @SuppressWarnings("unchecked")
593
    public static <T> Set<T> inter(final Set<T> a, final Set<T> b) {
594
        return (Set<T>) interSubtype(a, b);
595
    }
596
 
597
    public static <T> Set<? extends T> interSubtype(final Set<? extends T> a, final Set<? extends T> b) {
598
        if (a == b)
599
            return a;
600
        else if (a == null)
601
            return b;
602
        else if (b == null)
603
            return a;
604
        else if (a.size() > b.size()) {
605
            return interSubtype(b, a);
606
        }
607
 
608
        final Set<T> res = new HashSet<T>();
609
        for (final T item : a) {
610
            if (b.contains(item))
611
                res.add(item);
612
        }
613
        return res;
614
    }
615
 
616
    public static <T> Set<T> inter(final Set<T>... sets) {
617
        return inter(Arrays.asList(sets));
618
    }
619
 
620
    public static <T> Set<T> inter(final List<Set<T>> sets) {
621
        final List<Set<T>> mutable = new ArrayList<Set<T>>(sets.size());
622
        for (final Set<T> s : sets) {
623
            // ignore nulls
624
            if (s != null)
625
                mutable.add(s);
626
        }
627
 
628
        if (mutable.isEmpty())
629
            return null;
630
        else if (mutable.size() == 1)
631
            return mutable.get(0);
632
 
633
        final int indexMin = indexOfMinSize(mutable);
634
        if (indexMin != 0) {
635
            mutable.add(0, mutable.remove(indexMin));
636
            return inter(mutable);
637
        }
638
 
639
        if (mutable.get(0).isEmpty())
640
            return Collections.emptySet();
641
 
642
        // replace the first 2 by their intersection
643
        // (inter will swap as appropriate if java doesn't evalute args in source order)
644
        mutable.add(0, inter(mutable.remove(0), mutable.remove(0)));
645
        return inter(mutable);
646
    }
647
 
648
    private static final <T> int indexOfMinSize(final List<Set<T>> sets) {
649
        if (sets.isEmpty())
650
            throw new IllegalArgumentException("empty sets");
651
 
652
        int res = 0;
653
        for (int i = 1; i < sets.size(); i++) {
654
            if (sets.get(i).size() < sets.get(res).size())
655
                res = i;
656
        }
657
        return res;
658
    }
659
 
660
    /**
661
     * Returns a {@link Set} containing the union of the given {@link Set}s.
662
     *
663
     * @param <T> type of items.
664
     * @param a the first set, must not be <code>null</code>
665
     * @param b the second set, must not be <code>null</code>
666
     * @return the union of the two.
667
     */
668
    public static <T> Set<T> union(final Set<? extends T> a, final Set<? extends T> b) {
669
        final Set<T> res = new HashSet<T>(a);
670
        if (a != b)
671
            res.addAll(b);
672
        return res;
673
    }
674
 
132 ilm 675
    public static <T> Set<T> union(final Collection<? extends Collection<? extends T>> colls) {
676
        return union(new HashSet<T>(), colls);
677
    }
678
 
679
    public static <T> List<T> cat(final Collection<? extends Collection<? extends T>> colls) {
680
        return union(new ArrayList<T>(), colls);
681
    }
682
 
683
    public static <T, C extends Collection<? super T>> C union(final C collector, final Collection<? extends Collection<? extends T>> colls) {
149 ilm 684
        return union(collector, colls, Transformer.<Collection<? extends T>> nopTransformer());
132 ilm 685
    }
686
 
687
    public static <T, C extends Collection<? super T>, A> C union(final C collector, final Collection<? extends A> colls, final ITransformer<? super A, ? extends Collection<? extends T>> transf) {
688
        for (final A coll : colls) {
689
            collector.addAll(transf.transformChecked(coll));
690
        }
691
        return collector;
692
    }
693
 
17 ilm 694
    public static <T> Collection<T> subtract(final Collection<T> a, final Collection<? extends T> b) {
174 ilm 695
        final Collection<T> res = a instanceof IdentitySet ? new LinkedIdentitySet<>(a) : new ArrayList<>(a);
696
        for (Iterator<? extends T> it = b.iterator(); it.hasNext();) {
697
            res.remove(it.next());
698
        }
699
        return res;
17 ilm 700
    }
701
 
702
    public static <T> Collection<T> substract(final Collection<T> a, final Collection<? extends T> b) {
174 ilm 703
        return subtract(a, b);
17 ilm 704
    }
705
 
83 ilm 706
    public static final <T> T coalesce(T o1, T o2) {
707
        return o1 != null ? o1 : o2;
708
    }
709
 
710
    public static final <T> T coalesce(T... objects) {
711
        for (T o : objects) {
712
            if (o != null)
713
                return o;
714
        }
715
        return null;
716
    }
717
 
17 ilm 718
    /**
132 ilm 719
     * Return the one and only item of <code>l</code>, otherwise <code>null</code>.
17 ilm 720
     *
721
     * @param <T> type of list.
722
     * @param l the list.
132 ilm 723
     * @param atMostOne <code>true</code> if the passed collection must not have more than one item.
724
     * @return the only item of <code>l</code>, <code>null</code> if there's not exactly one.
725
     * @throws IllegalArgumentException if <code>atMostOne</code> and <code>l.size() > 1</code>.
17 ilm 726
     */
132 ilm 727
    public static <T> T getSole(Collection<T> l, final boolean atMostOne) throws IllegalArgumentException {
728
        final int size = l.size();
729
        if (atMostOne && size > 1)
730
            throw new IllegalArgumentException("More than one");
731
        if (size != 1)
732
            return null;
733
        else if (l instanceof List)
734
            return ((List<T>) l).get(0);
735
        else
736
            return l.iterator().next();
17 ilm 737
    }
738
 
739
    public static <T> T getSole(Collection<T> l) {
132 ilm 740
        return getSole(l, false);
17 ilm 741
    }
742
 
743
    public static <T> T getFirst(Collection<T> l) {
744
        return l.size() > 0 ? l.iterator().next() : null;
745
    }
746
 
747
    /**
748
     * Return the first item of <code>l</code> if it isn't empty, otherwise <code>null</code>.
749
     *
750
     * @param <T> type of list.
751
     * @param l the list.
752
     * @return the first item of <code>l</code> or <code>null</code>.
753
     */
754
    public static <T> T getFirst(List<T> l) {
755
        return getNoExn(l, 0);
756
    }
757
 
758
    /**
759
     * Return the last item of <code>l</code> if it isn't empty, otherwise <code>null</code>.
760
     *
761
     * @param <T> type of list.
762
     * @param l the list.
763
     * @return the last item of <code>l</code> or <code>null</code>.
764
     */
765
    public static <T> T getLast(List<T> l) {
766
        return getNoExn(l, l.size() - 1);
767
    }
768
 
769
    /**
770
     * Return the item no <code>index</code> of <code>l</code> if it exists, otherwise
771
     * <code>null</code>.
772
     *
773
     * @param <T> type of list.
774
     * @param l the list.
775
     * @param index the wanted index.
776
     * @return the corresponding item of <code>l</code> or <code>null</code>.
777
     */
778
    public static <T> T getNoExn(List<T> l, int index) {
779
        return index >= 0 && index < l.size() ? l.get(index) : null;
780
    }
781
 
73 ilm 782
    @SuppressWarnings("rawtypes")
783
    private static final Iterator EMPTY_ITERATOR = new Iterator() {
784
        @Override
785
        public boolean hasNext() {
786
            return false;
787
        }
788
 
789
        @Override
790
        public Object next() {
791
            throw new NoSuchElementException();
792
        }
793
 
794
        @Override
795
        public void remove() {
796
            throw new UnsupportedOperationException();
797
        }
798
    };
799
 
800
    @SuppressWarnings("unchecked")
801
    public static <T> Iterator<T> emptyIterator() {
83 ilm 802
        return EMPTY_ITERATOR;
73 ilm 803
    }
804
 
805
    public static <T> LinkedList<T> toLinkedList(final Iterator<T> iter) {
806
        return addTo(iter, new LinkedList<T>());
807
    }
808
 
809
    public static <T> ArrayList<T> toArrayList(final Iterator<T> iter, final int estimatedSize) {
810
        return addTo(iter, new ArrayList<T>(estimatedSize));
811
    }
812
 
813
    public static <T, C extends Collection<? super T>> C addTo(final Iterator<T> iter, final C c) {
814
        while (iter.hasNext())
815
            c.add(iter.next());
816
        return c;
817
    }
818
 
819
    public static <T> ListIterator<T> getListIterator(final List<T> l, final boolean reversed) {
820
        if (!reversed)
821
            return l.listIterator();
822
 
823
        return reverseListIterator(l.listIterator(l.size()));
824
    }
825
 
826
    public static <T> ListIterator<T> reverseListIterator(final ListIterator<T> listIter) {
827
        if (listIter instanceof ReverseListIter)
828
            return ((ReverseListIter<T>) listIter).listIter;
829
        else
830
            return new ReverseListIter<T>(listIter);
831
    }
832
 
833
    private static final class ReverseListIter<T> implements ListIterator<T> {
834
        private final ListIterator<T> listIter;
835
 
836
        private ReverseListIter(ListIterator<T> listIter) {
837
            this.listIter = listIter;
838
        }
839
 
840
        @Override
841
        public boolean hasNext() {
842
            return this.listIter.hasPrevious();
843
        }
844
 
845
        @Override
846
        public T next() {
847
            return this.listIter.previous();
848
        }
849
 
850
        @Override
851
        public boolean hasPrevious() {
852
            return this.listIter.hasNext();
853
        }
854
 
855
        @Override
856
        public T previous() {
857
            return this.listIter.next();
858
        }
859
 
860
        @Override
861
        public int nextIndex() {
862
            return this.listIter.previousIndex();
863
        }
864
 
865
        @Override
866
        public int previousIndex() {
867
            return this.listIter.nextIndex();
868
        }
869
 
870
        @Override
871
        public void remove() {
872
            this.listIter.remove();
873
        }
874
 
875
        @Override
876
        public void set(T e) {
877
            this.listIter.set(e);
878
        }
879
 
880
        @Override
881
        public void add(T e) {
882
            throw new UnsupportedOperationException();
883
        }
884
    }
885
 
142 ilm 886
    public static <T> List<T> createList(T item1, T item2) {
887
        final List<T> res = new ArrayList<T>();
888
        res.add(item1);
889
        res.add(item2);
890
        return res;
891
    }
892
 
893
    // workaround for lack of @SafeVarargs in Java 6, TODO use Arrays.asList() in Java 7
894
    public static <T> List<T> createList(T item1, T item2, T item3) {
895
        final List<T> res = createList(item1, item2);
896
        res.add(item3);
897
        return res;
898
    }
899
 
17 ilm 900
    public static <T> Set<T> createSet(T... items) {
901
        return new HashSet<T>(Arrays.asList(items));
902
    }
903
 
73 ilm 904
    public static <T> IdentitySet<T> createIdentitySet(T... items) {
67 ilm 905
        return new IdentityHashSet<T>(Arrays.asList(items));
906
    }
907
 
908
    /**
909
     * Return an {@link IdentitySet} consisting of <code>items</code>.
910
     *
911
     * @param items the collection whose elements are to be in the result.
912
     * @return a set, possibly <code>items</code> if it's already an identity set.
913
     */
914
    public static <T> Set<T> toIdentitySet(Collection<T> items) {
65 ilm 915
        if (items instanceof IdentitySet)
916
            return (Set<T>) items;
917
        else
918
            return new IdentityHashSet<T>(items);
919
    }
920
 
73 ilm 921
    @SuppressWarnings("rawtypes")
922
    private static final IdentitySet EMPTY_SET = new EmptyIdentitySet();
923
 
924
    @SuppressWarnings("unchecked")
925
    public static <T> IdentitySet<T> emptyIdentitySet() {
83 ilm 926
        return EMPTY_SET;
73 ilm 927
    }
928
 
929
    private static final class EmptyIdentitySet extends AbstractSet<Object> implements IdentitySet<Object>, Serializable {
930
        @Override
931
        public Iterator<Object> iterator() {
932
            return emptyIterator();
933
        }
934
 
935
        @Override
936
        public int size() {
937
            return 0;
938
        }
939
 
940
        @Override
941
        public boolean contains(Object obj) {
942
            return false;
943
        }
944
 
945
        // Preserves singleton property
946
        private Object readResolve() {
947
            return EMPTY_SET;
948
        }
949
    }
950
 
180 ilm 951
    public static final <T> List<T> toImmutableList(final Collection<? extends T> coll) {
952
        return toImmutableList(coll, ArrayList::new);
953
    }
954
 
955
    public static final <T, C extends Collection<? extends T>> List<T> toImmutableList(final C coll, final Function<? super C, ? extends List<T>> createColl) {
956
        if (coll.isEmpty())
957
            return Collections.emptyList();
958
        return Collections.unmodifiableList(createColl.apply(coll));
959
    }
960
 
961
    public static final <T> Set<T> toImmutableSet(final Collection<T> coll) {
962
        if (coll instanceof SortedSet) {
963
            // force TreeSet(SortedSet) to keep Comparator
964
            // ATTN see eclipse bug below about wrong constructor, we need SortedSet<T>, not
965
            // SortedSet<? extends T>, otherwise "Open Declaration" will match to TreeSet(SortedSet)
966
            // but not at runtime.
967
            return toImmutableSet((SortedSet<T>) coll, TreeSet::new);
968
        } else if (coll instanceof IdentitySet) {
969
            return toImmutableSet((IdentitySet<? extends T>) coll, LinkedIdentitySet::new);
970
        } else {
971
            // In doubt, keep order
972
            // ATTN LinkedHashSet extends HashSet
973
            return toImmutableSet(coll, coll.getClass() == HashSet.class ? HashSet::new : LinkedHashSet::new);
974
        }
975
    }
976
 
977
    public static final <T, C extends Collection<? extends T>> Set<T> toImmutableSet(final C coll, final Function<? super C, ? extends Set<T>> createColl) {
978
        if (coll.isEmpty())
979
            return Collections.emptySet();
980
        final Set<T> res = createColl.apply(coll);
981
        return Collections.unmodifiableSet(res);
982
    }
983
 
984
    /**
985
     * Return an immutable map equal to the passed one.
986
     *
987
     * @param <K> type of keys.
988
     * @param <V> type of values.
989
     * @param map the map, not "? extends K" to be able to copy {@link SortedMap}.
990
     * @return an immutable map.
991
     */
992
    public static final <K, V> Map<K, V> toImmutableMap(final Map<K, ? extends V> map) {
993
        if (map instanceof SortedMap) {
994
            // force TreeMap(SortedMap) to keep Comparator
995
            // ATTN see eclipse bug below about wrong constructor
996
            return toImmutableMap((SortedMap<K, ? extends V>) map, TreeMap::new);
997
        } else if (map instanceof IdentityHashMap) {
998
            return toImmutableMap((IdentityHashMap<? extends K, ? extends V>) map, IdentityHashMap::new);
999
        } else {
1000
            // In doubt, keep order
1001
            // ATTN LinkedHashMap extends HashMap
1002
            return toImmutableMap(map, map.getClass() == HashMap.class ? HashMap::new : LinkedHashMap::new);
1003
        }
1004
    }
1005
 
1006
    /**
1007
     * Return an immutable map with the same entries as the passed one. NOTE: <code>copyMap</code>
1008
     * <strong>must</strong> copy the entries so that a modification of <code>map</code> doesn't
1009
     * affect the copy.
1010
     *
1011
     * @param <K> type of keys.
1012
     * @param <V> type of values.
1013
     * @param <InMap> type of passed map, ATTN if {@link SortedMap} eclipse "Open Declaration"
1014
     *        matches <code>TreeMap::new</code> to {@link TreeMap#TreeMap(SortedMap)} ignoring
1015
     *        generic type (i.e. it is declared with "K" but we pass "? extends K") but
1016
     *        {@link TreeMap#TreeMap(Map)} is (correctly) executed at runtime.
1017
     * @param map the map.
1018
     * @param copyFunction how to copy the passed map.
1019
     * @return an immutable map.
1020
     */
1021
    public static final <K, V, InMap extends Map<? extends K, ? extends V>> Map<K, V> toImmutableMap(final InMap map, final Function<? super InMap, ? extends Map<K, V>> copyFunction) {
1022
        if (map.isEmpty())
1023
            return Collections.emptyMap();
1024
        return Collections.unmodifiableMap(copyFunction.apply(map));
1025
    }
1026
 
17 ilm 1027
    public static <K, V> Map<K, V> createMap(K key, V val, K key2, V val2) {
80 ilm 1028
        // arguments are ordered, so should the result
1029
        final Map<K, V> res = new LinkedHashMap<K, V>();
17 ilm 1030
        res.put(key, val);
1031
        res.put(key2, val2);
1032
        return res;
1033
    }
1034
 
1035
    public static <K, V> Map<K, V> createMap(K key, V val, K key2, V val2, K key3, V val3) {
1036
        final Map<K, V> res = createMap(key, val, key2, val2);
1037
        res.put(key3, val3);
1038
        return res;
1039
    }
1040
 
149 ilm 1041
    @SafeVarargs
1042
    public static <T> Map<T, T> createMapFromList(final T... keyAndVal) {
1043
        return createMapFromList(Arrays.asList(keyAndVal));
1044
    }
1045
 
1046
    public static <T> Map<T, T> createMapFromList(final List<T> keyAndVal) {
1047
        final int size = keyAndVal.size();
1048
        if (size % 2 != 0)
1049
            throw new IllegalArgumentException(size + " is not an even number of values : " + keyAndVal);
1050
        // arguments are ordered, so should the result
1051
        final Map<T, T> res = new LinkedHashMap<>(size);
1052
        for (int i = 0; i < size; i += 2) {
1053
            res.put(keyAndVal.get(i), keyAndVal.get(i + 1));
1054
        }
1055
        return res;
1056
    }
1057
 
17 ilm 1058
    /**
1059
     * Creates a map with null values.
1060
     *
1061
     * @param <K> type of key.
1062
     * @param <V> type of value.
1063
     * @param keys the keys of the map.
174 ilm 1064
     * @return a new ordered map.
17 ilm 1065
     */
1066
    public static <K, V> Map<K, V> createMap(Collection<? extends K> keys) {
174 ilm 1067
        // there's no way to tell if a Collection is ordered, so always use ordered map.
1068
        return fillMap(new LinkedHashMap<K, V>(keys.size()), keys);
17 ilm 1069
    }
1070
 
1071
    /**
1072
     * Fills a map with null values.
1073
     *
1074
     * @param <K> type of key.
1075
     * @param <V> type of value.
1076
     * @param <M> type of map.
1077
     * @param m the map to fill.
1078
     * @param keys the keys to add.
1079
     * @return the passed map.
1080
     */
1081
    public static <K, V, M extends Map<K, V>> M fillMap(final M m, Collection<? extends K> keys) {
80 ilm 1082
        return fillMap(m, keys, null);
1083
    }
1084
 
1085
    /**
1086
     * Fills a map with the same value.
1087
     *
1088
     * @param <K> type of key.
1089
     * @param <V> type of value.
1090
     * @param <M> type of map.
1091
     * @param m the map to fill.
1092
     * @param keys the keys to add.
83 ilm 1093
     * @param val the value to put.
80 ilm 1094
     * @return the passed map.
1095
     */
1096
    public static <K, V, M extends Map<K, V>> M fillMap(final M m, final Collection<? extends K> keys, final V val) {
17 ilm 1097
        for (final K key : keys)
80 ilm 1098
            m.put(key, val);
17 ilm 1099
        return m;
1100
    }
132 ilm 1101
 
1102
    public static <K, V, M extends Map<K, V>> M invertMap(final M m, final Map<? extends V, ? extends K> source) {
1103
        for (final Entry<? extends V, ? extends K> e : source.entrySet()) {
1104
            m.put(e.getValue(), e.getKey());
1105
        }
1106
        return m;
1107
    }
1108
 
1109
    public static <K, V, M extends CollectionMap2Itf<K, ?, V>> M invertMap(final M m, final Map<? extends V, ? extends K> source) {
1110
        for (final Entry<? extends V, ? extends K> e : source.entrySet()) {
1111
            m.add(e.getValue(), e.getKey());
1112
        }
1113
        return m;
1114
    }
17 ilm 1115
}