私が考えることができる最高のものは、Iterator Patternを使用してカスタム コレクションのカスタム Iterator を作成することです
以下の例では、降順で反復する My Custom Collection と Custom Iterator を作成しました。
注 - これは Collections.reverseOrder() で実行できます。説明のために、私はそれを取りました。
package com.designpattern.behavioural.iteratorpattern;
/*
* Java Iterator Pattern
* Iterator Pattern allows to access the elements in an Object in a sequential manner rather than exposing the internal logic
* Use Case - Traverse on different way based on the requirement
*/
/*
* Iterator interface
*/
interface Iterator {
public boolean hasNext();
public Object next();
}
/*
* Repository interface
*/
interface MyCollection {
public Iterator getIterator();
}
/*
* Repository and iterator implementation
* Customized iteration - Iterate in reverse order
*/
class MyCustomCollection implements MyCollection {
RepositoryIterator iterator = null;
@Override
public Iterator getIterator() {
iterator = new RepositoryIterator();
return iterator;
}
private class RepositoryIterator implements Iterator {
String[] elements = {"1","2","3","4","5","6","7","8"};
int index = 0;
@Override
public boolean hasNext() {
if (index < elements.length) {
return true;
}
return false;
}
@Override
public Object next() {
if (this.hasNext()) {
index += 1;
return elements[elements.length-index];
}
return null;
}
}
}
public class IteratorPattern {
public static void main(String[] args) {
MyCollection myCollection = new MyCustomCollection();
for (Iterator iterator = myCollection.getIterator() ; iterator.hasNext();) {
System.out.println(iterator.next());
}
}
}
出力:
8 7 6 5 4 3 2 1