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

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

The 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;

/**
 * 

Iterables class.

* * @author Sergio.U.Bocchio * @version $Id: $Id */ public class Iterables { /** *

decorate.

* * @param source a {@link java.lang.Iterable} object * @param transform a {@link java.util.function.Function} object * @param filter a {@link java.util.function.Predicate} object * @param a U class * @param a T class * @return a {@link com.ulisesbocchio.jasyptspringboot.util.Iterables.IterableDecorator} object */ static public IterableDecorator decorate(Iterable source, Function transform, Predicate filter) { return new IterableDecorator<>(source, transform, filter); } /** *

transform.

* * @param source a {@link java.lang.Iterable} object * @param transform a {@link java.util.function.Function} object * @param a U class * @param a T class * @return a {@link com.ulisesbocchio.jasyptspringboot.util.Iterables.IterableDecorator} object */ static public IterableDecorator transform(Iterable source, Function transform) { return new IterableDecorator<>(source, transform, v -> true); } /** *

filter.

* * @param source a {@link java.lang.Iterable} object * @param filter a {@link java.util.function.Predicate} object * @param a T class * @return a {@link com.ulisesbocchio.jasyptspringboot.util.Iterables.IterableDecorator} object */ 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(); } } }