Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to get Iterator<Character> from String [duplicate]

I need a Iterator<Character> from a String object. Is there any available function in Java that provides me this or do I have to code my own?

like image 461
Albert Avatar asked Oct 13 '10 15:10

Albert


People also ask

How do you find the occurrence of each character in a string Java?

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.

Can I copy iterator?

There's no way one could copy the current state of an iterator. The same happens to our original generator + promise usage. We could use the same syntax to work with events (i.e. repetitive callback calls), not just series of nested callbacks, but we don't have that vital iter. copy() method.


2 Answers

One option is to use Guava:

ImmutableList<Character> chars = Lists.charactersOf(someString); UnmodifiableListIterator<Character> iter = chars.listIterator(); 

This produces an immutable list of characters that is backed by the given string (no copying involved).

If you end up doing this yourself, though, I would recommend not exposing the implementation class for the Iterator as a number of other examples do. I'd recommend instead making your own utility class and exposing a static factory method:

public static Iterator<Character> stringIterator(final String string) {   // Ensure the error is found as soon as possible.   if (string == null)     throw new NullPointerException();    return new Iterator<Character>() {     private int index = 0;      public boolean hasNext() {       return index < string.length();     }      public Character next() {       /*        * Throw NoSuchElementException as defined by the Iterator contract,        * not IndexOutOfBoundsException.        */       if (!hasNext())         throw new NoSuchElementException();       return string.charAt(index++);     }      public void remove() {       throw new UnsupportedOperationException();     }   }; } 
like image 50
ColinD Avatar answered Sep 23 '22 06:09

ColinD


It doesn't exist, but it's trivial to implement:

class CharacterIterator implements Iterator<Character> {      private final String str;     private int pos = 0;      public CharacterIterator(String str) {         this.str = str;     }      public boolean hasNext() {         return pos < str.length();     }      public Character next() {         return str.charAt(pos++);     }      public void remove() {         throw new UnsupportedOperationException();     } } 

The implementation is probably as efficient as it gets.

like image 29
aioobe Avatar answered Sep 19 '22 06:09

aioobe