Class IteratorUtils


  • public class IteratorUtils
    extends Object
    Utility methods for Iterator conversions.
    • Method Detail

      • toIterable

        @NotNull
        public static <T> @NotNull Iterable<T> toIterable​(@NotNull
                                                          @NotNull Iterator<T> iterator)
        Convert an Iterator to an Iterable.

        This method is not thread-safe

        Parameters:
        iterator - iterator to convert
        Returns:
        a single-use iterable for the iterator (representing the remaining elements in the iterator)
        Throws:
        IllegalStateException - when Iterable.iterator() is called more than once
      • mergeSorted

        public static <T> Iterator<T> mergeSorted​(Iterable<? extends Iterator<? extends T>> itrs,
                                                  Comparator<? super T> c)
        Merges multiple sorted iterators into a single sorted iterator. Equivalent entries will not be de-duplicated.

        This method assumes that the input iterators are sorted in increasing order.

        Type Parameters:
        T - the type of elements returned by this iterator
        Parameters:
        itrs - the iterators to merge, must not be null
        c - the comparator to determine the order of elements, must not be null
        Returns:
        an iterator that merges the input iterators in sorted order
        Throws:
        NullPointerException - if the iterators or comparator are null
      • elementsEqual

        public static boolean elementsEqual​(Iterator<?> iterator1,
                                            Iterator<?> iterator2)
        Compares two iterators to determine if they contain the same elements in the same order.

        This method iterates through both iterators and compares each corresponding pair of elements.

        Note that this method consumes both iterators.

        Parameters:
        iterator1 - the first iterator to compare, may be null
        iterator2 - the second iterator to compare, may be null
        Returns:
        true if both iterators contain the same number of elements and all corresponding elements are equal, false otherwise.
      • size

        public static int size​(Iterator<?> iterator)
        Returns the number of elements in the given iterator.

        This method consumes the iterator to count the elements. A null or empty iterator returns 0.

        Parameters:
        iterator - the iterator whose size is to be determined
        Returns:
        the number of elements in the iterator
      • get

        public static <T> T get​(Iterator<T> iterator,
                                int index)
        Returns the element at the specified position in the iterator.

        This method will consume the iterator up to the specified position.

        Type Parameters:
        T - the type of elements in the iterator
        Parameters:
        iterator - the iterator to get the element from, must not be null
        index - the position of the element to return, zero-based
        Returns:
        the element at the specified position
        Throws:
        NullPointerException - if the iterator is null
        IndexOutOfBoundsException - if the iterator is empty or index is negative or greater than the number of elements in the iterator
      • getLast

        public static <T> T getLast​(Iterator<T> iterator)
        Returns the last element in the given iterator.

        This method consumes the entire iterator to find the last element.

        Type Parameters:
        T - the type of elements in the iterator
        Parameters:
        iterator - the iterator to get the last element from, must not be null
        Returns:
        the last element in the iterator
        Throws:
        NullPointerException - if the iterator is null
        NoSuchElementException - if the iterator is empty
      • contains

        public static boolean contains​(Iterator<?> iterator,
                                       Object element)
        Checks if the given iterator contains the specified element.

        This method iterates through the iterator, checking each element for equality with the specified object using Objects.equals(Object, Object). The iteration stops once a match is found or the iterator is exhausted.

        Note that this method will consume the iterator.

        Parameters:
        iterator - the iterator to check, must not be null
        element - the element to find, may be null
        Returns:
        true if the iterator contains the element, false otherwise
        Throws:
        NullPointerException - if the iterator is null
      • toArray

        public static <T> T[] toArray​(Iterator<? extends T> iterator,
                                      Class<T> type)
        Converts an iterator to an array of a specific type.

        This method consumes the iterator and returns an array containing all of its elements. The type of the array is determined by the provided type parameter.

        Type Parameters:
        T - the component type of the resulting array
        Parameters:
        iterator - the iterator to convert, must not be null
        type - the Class object representing the component type of the array, must not be null
        Returns:
        an array containing all the elements from the iterator
        Throws:
        NullPointerException - if the iterator or type is null
      • asEnumeration

        public static <T> Enumeration<T> asEnumeration​(Iterator<T> iterator)
        Converts an iterator to an enumeration.

        This method creates an Enumeration that will use the provided Iterator as its source of elements. The enumeration will iterate through the same elements as the iterator in the same order.

        The enumeration's hasMoreElements() and nextElement() methods delegate to the iterator's hasNext() and next() methods respectively.

        Type Parameters:
        T - the type of elements in the iterator and enumeration
        Parameters:
        iterator - the iterator to convert to an enumeration, must not be null
        Returns:
        an enumeration that uses the provided iterator as its source
        Throws:
        NullPointerException - if the iterator is null
      • chainedIterator

        public static <E> Iterator<E> chainedIterator​(Iterator<? extends E> iterator1,
                                                      Iterator<? extends E> iterator2)
        Returns an iterator that iterates through two iterators in sequence.

        This method creates a new iterator that will first iterate through the elements in the first iterator and then, when the first iterator is exhausted, will iterate through the elements in the second iterator.

        The returned iterator supports Iterator.remove() if the provided iterators support it.

        Type Parameters:
        E - the element type
        Parameters:
        iterator1 - the first iterator to chain, may be null
        iterator2 - the second iterator to chain, may be null
        Returns:
        an iterator that chains the specified iterators together
        Throws:
        NullPointerException - if any of the iterator is null
      • chainedIterator

        @SafeVarargs
        public static <E> Iterator<E> chainedIterator​(Iterator<? extends E>... iterators)
        Returns an iterator that iterates through varargs of iterators in sequence.

        This method creates a new iterator that will first iterate through the elements in the first iterator and then, when the first iterator is exhausted, will iterate through the elements in the second iterator and so on...

        The returned iterator supports Iterator.remove() if the underlying iterator support it.

        Type Parameters:
        E - the element type
        Parameters:
        iterators - array of iterators to chain must not be null
        Returns:
        an iterator that chains the specified iterators together
        Throws:
        NullPointerException - if iterators array is null or contains a null iterator
      • chainedIterator

        public static <E> Iterator<E> chainedIterator​(Collection<Iterator<? extends E>> iterators)
        Returns an iterator that iterates through a collection of iterators in sequence.

        This method creates a new iterator that will first iterate through the elements in the first iterator and then, when the first iterator is exhausted, will iterate through the elements in the second iterator and so on...

        The returned iterator supports Iterator.remove() if the underlying iterator support it.

        Type Parameters:
        E - the element type
        Parameters:
        iterators - collection of iterators to chain must not be null
        Returns:
        an iterator that chains the specified iterators together
        Throws:
        NullPointerException - if an iterators collection is null or contains a null iterator
      • chainedIterator

        public static <E> Iterator<E> chainedIterator​(Iterator<? extends Iterator<? extends E>> iterators)
        Returns an iterator that iterates through an iterator of iterators in sequence.

        This method creates a new iterator that will first iterate through the elements in the first iterator and then, when the first iterator is exhausted, will iterate through the elements in the second iterator and so on...

        The returned iterator supports Iterator.remove() if the underlying iterator support it.

        Type Parameters:
        E - the element type
        Parameters:
        iterators - an iterator of iterators to chain must not be null
        Returns:
        an iterator that chains the specified iterators together
        Throws:
        NullPointerException - if an iterators collection is null or contains a null iterator
      • filter

        public static <T> Iterator<T> filter​(Iterator<? extends T> itr,
                                             Predicate<? super T> predicate)
        Returns an iterator containing only the elements that match the given predicate.

        This method creates a new iterator that will iterate through elements from the source iterator but only return elements that satisfy the specified predicate. The filtering occurs during iteration and the method doesn't consume the source iterator until the returned iterator is advanced.

        Example usage:

         Iterator<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5).iterator();
         Predicate<Integer> isEven = n -> n % 2 == 0;
         Iterator<Integer> evenNumbers = IteratorUtils.filter(numbers, isEven);
         // evenNumbers will iterate through 2, 4
         

        The returned iterator supports Iterator.remove() if the source iterator supports it.

        Type Parameters:
        T - the type of objects in the iterator
        Parameters:
        itr - the source iterator, must not be null
        predicate - the predicate to apply to each element, must not be null
        Returns:
        a filtered iterator
        Throws:
        NullPointerException - if either the iterator or predicate is null
      • transform

        public static <F,​T> Iterator<T> transform​(Iterator<? extends F> itr,
                                                        Function<? super F,​? extends T> transform)
        Returns an iterator that transforms the elements of another iterator.

        This method creates a new iterator that will apply the given transformation function to each element of the source iterator as the new iterator is traversed. Transformations occur lazily during iteration and the source iterator is not consumed until the returned iterator is advanced.

        Example usage:

         Iterator<Integer> numbers = Arrays.asList(1, 2, 3).iterator();
         Function<Integer, String> toString = n -> "Number: " + n;
         Iterator<String> stringNumbers = IteratorUtils.transform(numbers, toString);
         // stringNumbers will iterate through "Number: 1", "Number: 2", "Number: 3"
         

        The returned iterator supports Iterator.remove() if the source iterator supports it.

        Type Parameters:
        F - the type of elements in the source iterator
        T - the type of elements in the transformed iterator
        Parameters:
        itr - the source iterator to transform, must not be null
        transform - the function to transform the elements of the source iterator, must not be null
        Returns:
        an iterator that transforms the elements of the source iterator
        Throws:
        NullPointerException - if either the iterator or the transform function is null
      • cycle

        @SafeVarargs
        public static <E> Iterator<E> cycle​(E... elements)
        Creates an iterator that cycles indefinitely over the provided elements.

        The returned iterator will continuously loop through the given elements in the same order. If no elements are provided, the iterator will be empty.

        Example usage:

         Iterator<String> cyclingIterator = IteratorUtils.cycle("a", "b", "c");
         // Iterates: "a", "b", "c", "a", "b", "c", ...
         
        Type Parameters:
        E - the type of elements in the iterator
        Parameters:
        elements - the elements to cycle through, must not be null
        Returns:
        an iterator that cycles indefinitely over the provided elements
        Throws:
        NullPointerException - if the elements array is null
      • cycle

        public static <E> Iterator<E> cycle​(Iterable<E> iterable)
        Creates an iterator that cycles indefinitely over the elements of the given iterable.

        The returned iterator will continuously loop through the elements of the iterable in the same order. If the iterable is empty, the iterator will also be empty.

        Example usage:

         List<String> list = Arrays.asList("a", "b", "c");
         Iterator<String> cyclingIterator = IteratorUtils.cycle(list);
         // Iterates: "a", "b", "c", "a", "b", "c", ...
         
        Type Parameters:
        E - the type of elements in the iterable
        Parameters:
        iterable - the iterable to cycle through, must not be null
        Returns:
        an iterator that cycles indefinitely over the elements of the iterable
        Throws:
        NullPointerException - if the iterable is null
      • partition

        public static <T> Iterator<List<T>> partition​(Iterator<T> iterator,
                                                      int size)
        Returns an iterator that partitions the elements of another iterator into fixed-size lists.

        This method creates a new iterator that will group elements from the source iterator into lists of the specified size. The final list may be smaller than the requested size if there are not enough elements remaining in the source iterator.

        The returned lists are unmodifiable. The source iterator is consumed only as the returned iterator is advanced.

        Example usage:

         Iterator<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5).iterator();
         Iterator<List<Integer>> partitioned = IteratorUtils.partition(numbers, 2);
         // partitioned will iterate through [1, 2], [3, 4], [5]
         
        Type Parameters:
        T - the type of elements in the source iterator
        Parameters:
        iterator - the source iterator to partition, must not be null
        size - the size of each partition, must be greater than 0
        Returns:
        an iterator of fixed-size lists containing the elements of the source iterator
        Throws:
        NullPointerException - if the iterator is null
        IllegalArgumentException - if size is less than or equal to 0
      • limit

        public static <T> Iterator<T> limit​(Iterator<T> iterator,
                                            int limit)
        Returns an iterator that will only provide at most the first N elements from given iterator.

        This method returns an iterator that will stop after returning the specified number of elements or when the source iterator is exhausted, whichever comes first.

        Example usage:

         Iterator<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David").iterator();
         Iterator<String> firstTwo = IteratorUtils.limit(names, 2);
         // firstTwo will iterate through "Alice", "Bob" only
         
        Type Parameters:
        T - the type of elements in the iterator
        Parameters:
        iterator - the source iterator to limit, must not be null
        limit - the maximum number of elements to return, must not be negative
        Returns:
        an iterator limited to the specified number of elements
        Throws:
        NullPointerException - if the iterator is null
        IllegalArgumentException - if limit is negative