Converts a string to an iterator of characters. - Java Collection Framework

Java examples for Collection Framework:Iterator

Description

Converts a string to an iterator of characters.

Demo Code


//package com.java2s;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    /**/*from  w w  w.  jav  a2s.  c o  m*/
     * Converts a string to an iterator of characters.
     */
    public static Iterator<Character> toIterator(final String value) {
        return new Iterator<Character>() {
            int index = 0;

            @Override
            public boolean hasNext() {
                return index < value.length();
            }

            @Override
            public Character next() {
                return value.charAt(index++);
            }

            @Override
            public void remove() {
            }
        };
    }

    /**
     * Wraps a map iterator with an iterator that returns tuples of [key,
     * value].
     */
    public static Iterator<?> toIterator(Map<?, ?> o) {
        final Iterator<?> it = o.entrySet().iterator();

        return new Iterator<Object>() {
            @Override
            public boolean hasNext() {
                return it.hasNext();
            }

            @Override
            public Object next() {
                Map.Entry<?, ?> entry = (Entry<?, ?>) it.next();
                return new Object[] { entry.getKey(), entry.getValue() };
            }

            @Override
            public void remove() {
            }
        };
    }
}

Related Tutorials