001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package org.pgpainless.util;
006
007import java.lang.reflect.Array;
008import java.util.ArrayList;
009import java.util.Iterator;
010import java.util.List;
011
012public final class CollectionUtils {
013
014    private CollectionUtils() {
015
016    }
017
018    /**
019     * Return all items returned by the {@link Iterator} as a {@link List}.
020     *
021     * @param iterator iterator
022     * @param <I> type
023     * @return list
024     */
025    public static <I> List<I> iteratorToList(Iterator<I> iterator) {
026        List<I> items = new ArrayList<>();
027        while (iterator.hasNext()) {
028            I item = iterator.next();
029            items.add(item);
030        }
031        return items;
032    }
033
034    /**
035     * Return a new array which contains <pre>t</pre> as first element, followed by the elements of <pre>ts</pre>.
036     * @param t head
037     * @param ts tail
038     * @param <T> type
039     * @return t and ts as array
040     */
041    public static <T> T[] concat(T t, T[] ts) {
042        T[] concat = (T[]) Array.newInstance(t.getClass(), ts.length + 1);
043        concat[0] = t;
044        System.arraycopy(ts, 0, concat, 1, ts.length);
045        return concat;
046    }
047
048    /**
049     * Return true, if the given array <pre>ts</pre> contains the element <pre>t</pre>.
050     * @param ts elements
051     * @param t searched element
052     * @param <T> type
053     * @return true if ts contains t, false otherwise
054     */
055    public static <T> boolean contains(T[] ts, T t) {
056        for (T i : ts) {
057            if (i.equals(t)) {
058                return true;
059            }
060        }
061        return false;
062    }
063}