Selective Iterator demo for Iterator Pattern in Java
In my earlier post, I have shown demo of External Complete Reverse Iterator for Iterator Pattern.In this post, I am going to show demo of External and Internal Selective Iterator done in Java. Selective Iterator iterates through the collection but leaves the elements which do not meet criteria specified in predicate logic.
For this to implement using Iterator pattern, major requirements are : functor interface, concrete functor class, predicate interface, concrete predicate class, customized collection (like Vector, Arraylist), Object class, selective Iterator and main application.
Functor interface and class are used to implement certain function. The function is included in an object which executes the function based on input parameters. The functor call is like below.
Functor<Swimmer> functor = new SwimmerFunctor(JTextArea2);
functor.process(swimmer);
And its implementation is like below.
public void process(Swimmer swimmer){
textArea.append(swimmer.getFname()+” “+swimmer.getLname()+ ” \n”);
}
Using this technique to delegate work to another object is called functor pattern.
Predicate is also a special functor but it always return true or false. In my example, I have used predicate to check whether the age of swimmer is above or equal to 12 or not.
A selective Iterator uses predicate to check whether to iterate through a particular element or not.
The iteration loop becomes like this
Functor<Swimmer> functor = new SwimmerFunctor(JTextArea2);
Predicate<Swimmer> pred = new SwimmerPredicate();
Iterator<Swimmer> swIterator = slist.selectiveIterator(pred);
while(swIterator.hasNext()){
Swimmer swimmer = swIterator.next();
functor.process(swimmer);
}
If iteration is placed inside the collection, then it becomes Internal selective Iteration. If placed outside, it becomes External Selective Iteratoration.
In the demo, I have created Swimmer as object and added 9 swimmers of age 11 and 12 to customized concrete collection of type myList. An external complete built-in iterator is used to populate all the swimmers in first JTextArea of JFrame. The selective external iterator is used to populate swimmers that have age of 12 or greater in the second JTextArea of the JFrame. Also, I have created a method inside myList named doAll(Functor<T> functor, Predicate<T> pred) which does selective iteration inside the myList i.e. Internal Selective Iteration.