org.securegraph.util.IterableUtils Maven / Gradle / Ivy
The newest version!
package org.securegraph.util;
import java.io.Closeable;
import java.lang.reflect.Array;
import java.util.*;
public class IterableUtils {
@SuppressWarnings("unchecked")
public static List toList(Iterable extends T> iterable) {
if (iterable instanceof List) {
return (List) iterable;
}
List results = new ArrayList();
for (T o : iterable) {
results.add(o);
}
close(iterable);
return results;
}
@SuppressWarnings("unchecked")
public static Set toSet(Iterable extends T> iterable) {
if (iterable instanceof Set) {
return (Set) iterable;
}
Set results = new HashSet();
for (T o : iterable) {
results.add(o);
}
close(iterable);
return results;
}
@SuppressWarnings("unchecked")
public static Set toSet(T[] iterable) {
Set results = new HashSet();
Collections.addAll(results, iterable);
return results;
}
@SuppressWarnings("unchecked")
public static T[] toArray(Iterable extends T> iterable, Class type) {
List extends T> list = toList(iterable);
T[] array = (T[]) Array.newInstance(type, list.size());
return list.toArray(array);
}
public static int count(Iterable iterable) {
int count = 0;
for (T ignore : iterable) {
count++;
}
close(iterable);
return count;
}
public static Iterable toIterable(final T[] arr) {
return new Iterable() {
@Override
public Iterator iterator() {
return new Iterator() {
int index = 0;
@Override
public boolean hasNext() {
return index < arr.length;
}
@Override
public T next() {
return arr[index++];
}
@Override
public void remove() {
throw new RuntimeException("Not supported");
}
};
}
};
}
public static T single(final Iterable extends T> it) {
Iterator extends T> i = it.iterator();
if (!i.hasNext()) {
throw new IllegalStateException("No items found.");
}
T result = i.next();
if (i.hasNext()) {
close(it);
throw new IllegalStateException("More than 1 item found.");
}
close(it);
return result;
}
private static void close(Iterable extends T> it) {
if (it instanceof Closeable) {
CloseableUtils.closeQuietly((Closeable) it);
}
}
public static T singleOrDefault(final Iterable extends T> it, T defaultValue) {
Iterator extends T> i = it.iterator();
if (!i.hasNext()) {
return defaultValue;
}
T result = i.next();
if (i.hasNext()) {
close(it);
throw new IllegalStateException("More than 1 item found.");
}
close(it);
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy