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

org.aksw.commons.collections.CollectionUtils Maven / Gradle / Ivy

There is a newer version: 0.9.9
Show newest version
package org.aksw.commons.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

/**
 * User: raven
 * Date: 4/17/11
 * Time: 12:36 AM
 */
public class CollectionUtils {

	/**
	 * Create a new collection and initialize it with items from an iterator
	 * Mainly useful in cases where use of guava could cause issues (e.g. hadoop/spark)
	 */
	public static > C newCollection(Supplier collectionSupplier, Iterator itemIt) {
		C result = collectionSupplier.get();
		while (itemIt.hasNext() ) {
			T item = itemIt.next();
			result.add(item);
		}
		return result;
	}

	/**
	 * Create a new collection and initialize it with items from an iterable
	 * Mainly useful in cases where use of guava could cause issues (e.g. hadoop/spark)
	 */
	public static > C newCollection(Supplier collectionSupplier, Iterable items) {
		return newCollection(collectionSupplier, items.iterator());
	}

	
    /**
     * Given an iterable A whose elements are iterables, this method will return the first
     * element of A.
     * If no such element exist, an empty iterable is returned rather than null.
     *
     *
     * @param iterable
     * @param 
     * @param 
     * @return
     */
    public static > Iterable safeGetFirst(Iterable iterable) {
        Iterator it = iterable.iterator();

        return it.hasNext() ? it.next() : Collections.emptySet();
    }

    public static  List> chunk(Iterable col, int batchSize)
    {
        List> result = new ArrayList>();

        List chunk = new ArrayList();

        Iterator it = col.iterator();
        while(it.hasNext()) {
            chunk.add(it.next());

            if(chunk.size() >= batchSize || !it.hasNext()) {
                result.add(chunk);

                if(it.hasNext())
                    chunk = new ArrayList();
            }
        }

        return result;
    }

    /** Transforms an array into a Hashset. @author Konrad Höffner */
    static  Set asSet(T[] a)
    {
        Set s = new HashSet();
        for(T e:a) {s.add(e);}
        return s;
    }
}