Java: how to get Iterator<Character> from String

Viewed 42717

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?

12 Answers

This feels dirty, but you could use Scanner with empty string delimiter:

Scanner scanner = new java.util.Scanner(myInput).useDelimiter("");

Scanner implements Iterator, so scanner is now an Iterator of length-1 strings, which is close.

To continue with the (very?) dirty, in Java 8 you can then do this to succinctly iterate by chars:

for (String s: (Iterable<String>)() -> scanner) { 
  char c = s.charAt(0);
  System.out.println(c); 
}

For details on why () -> scanner works (and why it may be dangerous, though not in this use case), see Explain how this lambda can be assigned to an Iterable.

Related