| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.tree.jiter; |
| 9 | |
| 10 | import java.util.Iterator; |
| 11 | import java.util.function.Supplier; |
| 12 | |
| 13 | /** |
| 14 | * An iterator over nodes, that concatenates the nodes returned by two supplied iterators. |
| 15 | */ |
| 16 | |
| 17 | public class ConcatenatingIterator<E> implements Iterator<E> { |
| 18 | |
| 19 | Iterator<? extends E> first; |
| 20 | Supplier<Iterator<? extends E>> second; |
| 21 | Iterator<? extends E> active; |
| 22 | |
| 23 | /** |
| 24 | * Create an iterator that concatenates the results of two supplied iterator. The |
| 25 | * second iterator isn't created until it is actually needed. |
| 26 | * @param first the first iterator |
| 27 | * @param second a function that can be called to supply the second iterator |
| 28 | */ |
| 29 | |
| 30 | public ConcatenatingIterator(Iterator<? extends E> first, Supplier<Iterator<? extends E>> second) { |
| 31 | this.first = first; |
| 32 | this.second = second; |
| 33 | this.active = first; |
| 34 | } |
| 35 | |
| 36 | @Override |
| 37 | public boolean hasNext() { |
| 38 | if (active.hasNext()) { |
| 39 | return true; |
| 40 | } else if (active == first) { |
| 41 | first = null; |
| 42 | active = second.get(); |
| 43 | return active.hasNext(); |
| 44 | } else { |
| 45 | return false; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Get the next item in the sequence. |
| 51 | * @return the next Item. If there are no more items, return null. |
| 52 | */ |
| 53 | |
| 54 | /*@Nullable*/ |
| 55 | public E next() { |
| 56 | return active.next(); |
| 57 | } |
| 58 | |
| 59 | } |
| 60 |