I have an Iterator<TypeA>
that I want to convert to Iterator<TypeB>
. TypeA and TypeB cannot be directly cast to each other but I can write a rule how to cast them. How can I accomplish this? Should I extend and override Iterator<TypeA>
's next, hasNext and remove methods?
There are three types of iterators. Enumeration − Enumeration is initial iterators introduced in jdk 1.0 and is only for older collections like vector or hashTables. Enumeration can be used for forward navigation only. Element can not be removed using Enumeration.
To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport. stream(), the spliterator can be traversed and then collected with the help collect() into collection.
You don't need to write this yourself. Guava (formerly Google-collections) has you covered in Iterators.transform(...)
You provide your iterator and a function that converts TypeA to TypeB and you're done.
Iterator<TypeA> iterA = ....;
Iterator<TypeB> iterB = Iterators.transform(iterA, new Function<TypeA, TypeB>() {
@Override
public TypeB apply(TypeA input) {
TypeB output = ...;// rules to create TypeB from TypeA
return output;
}
});
Write an adapter. Here's an example in Java. OReilly's book 'Head First: Design Patterns' gives the best explanation on the topic.
I guess you should write your own iterator(it can implements java.util.iterator) with your ((converting)) rule in a method and use it.
You can use the following snippet :
public static void main(String... args){
Iterator<TypeA> iteratorTypeA = methodToGetIteratorTypeA();
Iterator<TypeB> iteratorTypeB = new IteratorConveter<TypeA, TypeB>(iteratorTypeA,
new Converter<TypeA, TypeB>(){
public TypeB convert(TypeA typeA){
return null; //Something to convert typeA to type B
}
});
}
public class IteratorConveter<F, T> implements Iterator<T> {
private final Converter<? super F, ? extends T> converter;
private final Iterator<F> iterator;
public IteratorConveter(Iterator<F> iterator, Converter<? super F, ? extends T> converter) {
this.converter = converter;
this.iterator = iterator;
}
public boolean hasNext() {
return iterator.hasNext();
}
public T next() {
return converter.convert(iterator.next());
}
public void remove() {
iterator.remove();
}
}
interface Converter<F, T> {
T convert(F object);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With