package ru.yandex.wmtools.common.util;

import ru.yandex.common.util.collections.CollectionUtils;
import ru.yandex.common.util.functional.Filter;

import java.util.Iterator;
import java.util.List;

/**
 * @author avhaliullin
 */
public class CollectionUtil {
    public static <S, R> Iterable<R> wrapIterable(final Iterable<S> iterable, final Adapter<S, R> adapter) {
        return new Iterable<R>() {
            @Override
            public Iterator<R> iterator() {
                final Iterator<S> it = iterable.iterator();
                return new Iterator<R>() {
                    @Override
                    public boolean hasNext() {
                        return it.hasNext();
                    }

                    @Override
                    public R next() {
                        return adapter.adapt(it.next());
                    }

                    @Override
                    public void remove() {
                        it.remove();
                    }
                };
            }
        };
    }

    public static <T> List<T> removeNulls(List<T> list) {
        return CollectionUtils.filterList(list, new Filter<T>() {
            @Override
            public boolean fits(T t) {
                return t != null;
            }
        });
    }

    public interface Adapter<S, R> {
        public R adapt(S source);
    }
}
