All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.pgpainless.util.CollectionUtils Maven / Gradle / Ivy

There is a newer version: 1.6.7
Show newest version
// SPDX-FileCopyrightText: 2021 Paul Schaub 
//
// SPDX-License-Identifier: Apache-2.0

package org.pgpainless.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public final class CollectionUtils {

    private CollectionUtils() {

    }

    /**
     * Return all items returned by the {@link Iterator} as a {@link List}.
     *
     * @param iterator iterator
     * @param  type
     * @return list
     */
    public static  List iteratorToList(Iterator iterator) {
        List items = new ArrayList<>();
        while (iterator.hasNext()) {
            I item = iterator.next();
            items.add(item);
        }
        return items;
    }

    /**
     * Return a new array which contains 
t
as first element, followed by the elements of
ts
. * @param t head * @param ts tail * @param type * @return t and ts as array */ public static T[] concat(T t, T[] ts) { T[] concat = (T[]) Array.newInstance(t.getClass(), ts.length + 1); concat[0] = t; System.arraycopy(ts, 0, concat, 1, ts.length); return concat; } /** * Return true, if the given array
ts
contains the element
t
. * @param ts elements * @param t searched element * @param type * @return true if ts contains t, false otherwise */ public static boolean contains(T[] ts, T t) { for (T i : ts) { if (i.equals(t)) { return true; } } return false; } /** * Add all items from the iterator to the collection. * * @param type of item * @param iterator iterator to gather items from * @param collection collection to add items to */ public static void addAll(Iterator iterator, Collection collection) { while (iterator.hasNext()) { collection.add(iterator.next()); } } }