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

com.happy3w.toolkits.iterator.DistinctIterator Maven / Gradle / Ivy

There is a newer version: 1.2.0
Show newest version
package com.happy3w.toolkits.iterator;

import com.happy3w.java.ext.NeedFindIterator;
import com.happy3w.java.ext.NullableOptional;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;

public class DistinctIterator extends NeedFindIterator implements IEasyIterator {
    private final Iterator innerIt;
    private final Function keyGenerator;
    private Set existKeys = new HashSet<>();

    public DistinctIterator(Iterator innerIt, Function keyGenerator) {
        this.innerIt = innerIt;
        this.keyGenerator = keyGenerator;
    }

    @Override
    protected NullableOptional findNext() {
        while (innerIt.hasNext()) {
            T next = innerIt.next();
            Object key = keyGenerator.apply(next);
            if (existKeys.contains(key)) {
                continue;
            }

            existKeys.add(key);
            return NullableOptional.of(next);
        }
        return NullableOptional.empty();
    }
}