001package dev.tinyflow.core.util;
002
003import java.util.Collection;
004import java.util.Iterator;
005import java.util.List;
006
007public class IterableUtil {
008
009    public static boolean isEmpty(Iterable<?> iterable) {
010        if (iterable == null) {
011            return true;
012        }
013        if (iterable instanceof Collection) {
014            return ((Collection<?>) iterable).isEmpty();
015        }
016        return !iterable.iterator().hasNext();
017    }
018
019
020    public static boolean isNotEmpty(Iterable<?> iterable) {
021        return !isEmpty(iterable);
022    }
023
024    public static int size(Iterable<?> iterable) {
025        if (iterable == null) {
026            return 0;
027        }
028        if (iterable instanceof Collection) {
029            return ((Collection<?>) iterable).size();
030        }
031        int size = 0;
032        for (Iterator<?> it = iterable.iterator(); it.hasNext(); it.next()) {
033            size++;
034        }
035        return size;
036    }
037
038    public static <T> T get(Iterable<T> iterable, int index) {
039        if (iterable == null) {
040            throw new IllegalArgumentException("iterable must not be null");
041        }
042        if (index < 0) {
043            throw new IndexOutOfBoundsException("index < 0: " + index);
044        }
045
046        if (iterable instanceof List) {
047            List<T> list = (List<T>) iterable;
048            if (index >= list.size()) {
049                throw new IndexOutOfBoundsException("index >= size: " + index);
050            }
051            return list.get(index);
052        }
053
054        int i = 0;
055        for (T t : iterable) {
056            if (i == index) {
057                return t;
058            }
059            i++;
060        }
061
062        throw new IndexOutOfBoundsException("index >= size: " + index);
063    }
064}