I have a problem with my custom iterator, so I'm asking for your help. I have class MyIterator, which is an iterator with transformation. This class has methods:
- next() - returns next element
- hasNext() - check if next element exists
- fromIterator - static method, which converts Iterator to MyIterator
- map - method which takes functional interface and returns MyIterator with transformation rule corresponding to this interface
- forEach - method which takes functional interface and iterates over all remaining objects according to the interface.
My realisation is
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.function.Function;
public class MyIterator<K, V> {
private final Iterator<K> iterator;
private final Function<K, V> function;
@SuppressWarnings("unchecked")
public static <K, V> MyIterator<K, V> fromIterator(Iterator<K> iterator) {
return new MyIterator<>(iterator, k -> (V) k);
}
private MyIterator(Iterator<K> iterator, Function<K, V> function) {
this.iterator = iterator;
this.function = function;
}
public V next() {
return this.function.apply(iterator.next());
}
public boolean hasNext() {
return this.iterator.hasNext();
}
public MyIterator<K, V> map(Function<K, V> function) {
return new MyIterator<K, V>(this.iterator, this.function);
}
public void forEach(Consumer<V> action) {
while (hasNext()) {
action.accept(this.next());
}
}
}
So, I did this task, but I can't understand, how to change the method map into chaining method (pipeline). I mean the following:
MyIterator<String, Integer> myIterator3 = MyIterator.fromIterator(stringsArray.iterator()).map(s -> s.length()).map(i -> i.toString()).map(s -> s.length());
For example, I have String "England". After first map I want to get 7 ("England" consists of 7 characters), than "7", than 1 (because String "7" consists of 1 character).
My assumption is that I should use methods andThen/compose in my method map, by I can't understand, how.
mapmethod takes a function as a parameter which you completely ignore.k -> (V) kshould act as a clue that what you're doing does not make a lot of sensereturn new MyIterator(this.iterator, this.function.andThen(function));. Therefore, this approach is incorrect or I don't understand how this function works