-3

I have a class that stores String-type data that can be compared based on the length of the string ( compareTo() ), iterated by chars ( iterator() ).

I have implemented compareTo method but I don't know how to implement the iterator()

public class ExtendedString implements Comparable<ExtendedString>,Iterable<Character>{
    private String str;

    public ExtendedString(String str) {
        this.str = str;
    }

    public int compareTo(ExtendedString estr) {...}

    public Iterator<Character> iterator() {
        ???
    }
}

My question is how should I implement iterator()?

samabcde
  • 6,988
  • 2
  • 25
  • 41
GetHelp
  • 11
  • 2

1 Answers1

0
  1. To convert String to Character[], we can follow this answer
  2. Use Arrays#stream method to convert the Character[] to Stream<Character>, then use BaseStream#iterator.
@Override
public Iterator<Character> iterator() {
    return Arrays.stream(str.chars().mapToObj(c -> (char) c).toArray(Character[]::new)).iterator();
}
samabcde
  • 6,988
  • 2
  • 25
  • 41