Do I really need to implement an iterator in this case?

I need some tips on using Iterable<T> in Java.

I have the following class:

 public abstract class Validator implements Comparable<Validator>{ public abstract boolean validate(); public abstract int getPriority(); @Override public int compareTo(Validator o) { return getPriority() > o.getPriority() ? -1 : getPriority() == o.getPriority() ? 0 : 1; } } 

I need to create a ValidatorChain class as follows:

 public class ValidatorChain{ //Contains Collection<Validator> // and we can iterate over it with for-each loop in high-to-low priority order } 

Maybe I should just override some immediate implementation of Iterable<T> instead of writing my own from scratch.

+5
source share
2 answers

You can write it manually in a simple way, delegating to the collection iterator:

 public class ValidatorChain implements Iterable<Validator> { Collection<Validator> validators = ...; public Iterator<Validator> iterator() { return validators.iterator(); } } 

If you need to sort it, you can sort the validators collections or take a copy:

  public Iterator<Validator> iterator() { List<Validator> sorted = new ArrayList<> (validators); Collections.sort(sorted); return sorted.iterator(); } 

Or using Java 8:

  public Iterator<Validator> iterator() { return validators.stream().sorted().collect(toList()).iterator(); } 
+5
source

You can expand your ValidatorChain with the collection:

 public class ValidatorChain extends ArrayList<Validator>{ //... } 

Now it repeats, due to the expansion of the ArrayList array, which itself is iterable

+3
source

All Articles