aboutsummaryrefslogtreecommitdiffstats
path: root/tools/java/org/unicode/cldr/util/DelegatingIterator.java
blob: 4d02f24ec2b5dd413a16a9ff6191841d7478a171 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package org.unicode.cldr.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class DelegatingIterator<T> implements Iterator<T> {

    private Iterator<T>[] iterators;
    private int item = 0;

    @SuppressWarnings("unchecked")
    public DelegatingIterator(Iterator<T>... iterators) {
        this.iterators = iterators;
    }

    public boolean hasNext() {
        while (item < iterators.length) {
            boolean result = iterators[item].hasNext();
            if (result) {
                return true;
            }
            ++item;
        }
        return false;
    }

    public T next() {
        while (item < iterators.length) {
            try {
                return iterators[item].next();
            } catch (NoSuchElementException e) {
                ++item;
            }
        }
        throw new NoSuchElementException();
    }

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

    @SuppressWarnings("unchecked")
    public static <T> Iterable<T> iterable(Iterable<T>... s) {
        return new MyIterable<T>(s);
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] array(T... s) {
        return s;
    }

    private static class MyIterable<T> implements Iterable<T> {
        public Iterable<T>[] iterables;

        @SuppressWarnings("unchecked")
        public MyIterable(Iterable<T>... s) {
            iterables = s;
        }

        @SuppressWarnings("unchecked")
        public Iterator<T> iterator() {
            Iterator<T>[] iterators = new Iterator[iterables.length];
            for (int i = 0; i < iterables.length; ++i) {
                iterators[i] = iterables[i].iterator();
            }
            return new DelegatingIterator<T>(iterators);
        }
    }
}