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

com.ulisesbocchio.jasyptspringboot.util.Iterables Maven / Gradle / Ivy

There is a newer version: 3.0.5
Show newest version
package com.ulisesbocchio.jasyptspringboot.util;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Predicate;

public class Iterables {

    static public  IterableDecorator decorate(Iterable source, Function transform, Predicate filter) {
        return new IterableDecorator<>(source, transform, filter);
    }

    static public  IterableDecorator transform(Iterable source, Function transform) {
        return new IterableDecorator<>(source, transform, v -> true);
    }

    static public  IterableDecorator filter(Iterable source, Predicate filter) {
        return new IterableDecorator<>(source, Function.identity(), filter);
    }

    public static class IterableDecorator implements Iterable {
        private final Function transform;
        private final Predicate filter;
        private final Iterable source;

        IterableDecorator(Iterable source, Function transform, Predicate filter) {
            this.source = source;
            this.transform = transform;
            this.filter = filter;
        }

        @Override
        public Iterator iterator() {
            return new IteratorDecorator<>(this.source.iterator(), this.transform, this.filter);
        }
    }

    public static class IteratorDecorator implements Iterator {

        private final Iterator source;
        private final Function transform;
        private final Predicate filter;
        private T next = null;

        public IteratorDecorator(Iterator source, Function transform, Predicate filter) {
            this.source = source;
            this.transform = transform;
            this.filter = filter;
        }

        public boolean hasNext() {
            this.maybeFetchNext();
            return next != null;
        }

        public T next() {
            if (next == null) {
                throw new NoSuchElementException();
            }
            T val = next;
            next = null;
            return val;
        }

        private void maybeFetchNext() {
            if (next == null) {
                if (source.hasNext()) {
                    U val = source.next();
                    if (filter.test(val)) {
                        next = transform.apply(val);
                    }
                }
            }
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}