Java Iterator multiSetIterator(Iterator... iterable)

Here you can find the source of multiSetIterator(Iterator... iterable)

Description

multi Set Iterator

License

Open Source License

Declaration

public static <X> Iterator<X> multiSetIterator(Iterator<? extends X>... iterable) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

import java.util.HashSet;
import java.util.Iterator;

import java.util.NoSuchElementException;
import java.util.Set;

public class Main {
    public static <X> Iterator<X> multiSetIterator(Iterator<? extends X>... iterable) {
        return multiSetIterator(Arrays.asList(iterable));
    }//from   ww  w.j  a v  a2  s . c  om

    public static <X> Iterator<X> multiSetIterator(Iterator<? extends Iterator<? extends X>> iterable) {
        return new Iterator<X>() {

            Iterator<? extends X> curIter = null;
            Set<X> ret = new HashSet<>();
            boolean haveNext = false;
            X next = null;

            @Override
            public boolean hasNext() {
                if (haveNext) {
                    return true;
                }
                while (curIter.hasNext()) {
                    if (ret.add(next = curIter.next())) {
                        haveNext = true;
                        return true;
                    }
                }
                while (iterable.hasNext()) {
                    curIter = iterable.next();
                    if (curIter == null) {
                        continue;
                    }
                    while (curIter.hasNext()) {
                        if (ret.add(next = curIter.next())) {
                            haveNext = true;
                            return true;
                        }
                    }
                }
                return false;
            }

            @Override
            public X next() {
                if (hasNext()) {
                    haveNext = false;
                    return next;
                }
                throw new NoSuchElementException();
            }
        };
    }

    public static <X> Iterator<X> multiSetIterator(Iterable<? extends Iterator<? extends X>> iterable) {
        return multiSetIterator(iterable.iterator());
    }
}

Related

  1. mergeIterator( final Iterator iterator1, final Iterator iterator2)
  2. moveNext(Iterator iterator)
  3. multiIterator(Iterator... iterable)
  4. multiply(String string, Iterator placeholders, Iterator replacements)
  5. multiply(String string, Iterator placeholders, Iterator replacements)
  6. nextPermutation(Iterator> it)
  7. printContainer(Iterator it, String sep)
  8. printElements(String desc, Iterator i)
  9. printIterator(final Iterator iterator)