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

io.gsonfire.util.IterableMapper Maven / Gradle / Ivy

Go to download

A java library that adds some very useful features to Gson, like Date serializing to unix timestamp or RFC3339, method (getter) serialization, pre and post processors and many more. Check out the documentation to learn how to use it!

There is a newer version: 1.9.0
Show newest version
package io.gsonfire.util;

import java.util.Iterator;

/**
 * Created by julio on 6/24/15.
 */
public class IterableMapper implements Iterable {

    private final Iterable source;
    private final Mapper mapper;

    private IterableMapper(Iterable source, Mapper mapper) {
        this.source = source;
        this.mapper = mapper;
    }

    @Override
    public Iterator iterator() {
        final Iterator sourceIterator = source.iterator();
        return new Iterator() {
            @Override
            public boolean hasNext() {
                return sourceIterator.hasNext();
            }

            @Override
            public T next() {
                T mapped = mapper.map(sourceIterator.next());
                return mapped;
            }

            @Override
            public void remove() {

            }
        };
    }

    @Override
    public boolean equals(Object o) {
        if(o != null && o instanceof Iterable) {
            Iterator otherIterator = ((Iterable) o).iterator();
            Iterator thisIterator = this.iterator();
            while(thisIterator.hasNext()) {
                if(otherIterator.hasNext()) {
                    Object thisNext = thisIterator.next();
                    Object otherNext = otherIterator.next();
                    if(!areObjectEquals(thisNext, otherNext)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            return !otherIterator.hasNext();
        } else {
            return false;
        }
    }

    private static boolean areObjectEquals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }

    public static  Iterable create(Iterable source, Mapper mapper) {
        return new IterableMapper(source, mapper);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy