-2

I frequently would like to iterate over a view of some underlying data structure, e.g. a backwards iteration or only a slice of a list. The Java standard library has some support for multiple iterator views, e.g. with Map#keySet and Map#elemSet. I would like an API to quickly generate such views:

List<A> myList;
for (A it : iter(myList).from(24).backwards()) {
    ...
}

I would like an easy way to define these views ideally without being significantly slower than normal iterators.

2
  • 2
    It turns out Java 21 has these built in: myList.subList(0,25).reversed() gives the wanted (iterable) view without copying the list. The relevant documentation is here docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/… Commented Apr 14 at 9:07
  • FYI, List.subList(...) has existed since the introduction of the Collections Framework in Java 1.2. Commented Apr 15 at 9:32

1 Answer 1

1

Perhaps you can achieve this using ListIterator?

for (ListIterator<A> it = myList.listIterator(24); it.hasPrevious(); ) {
   A item = it.previous();
   ...
}

If you want from index 24 to 13 you could do

for (ListIterator<A> it = myList.listIterator(24); it.previousIndex() > 12; ) {
   A item = it.previous();
   ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

As soon as I want a different step size, or only iterate from 24 to 13, this becomes awkward. It's usable, but it requires some concentration whenever someone reads the code ``` var iter = list.listIterator(24); int i = 24; while (iter.hasPrevious) { if (i-- <= 12) { break; } var item = iter.previous(); ... } ```
ListIterator has previousIndex() and nextIndex() methods so you could do for (ListIterator<A> it = myList.listIterator(24); it.previousIndex() > 12; ). Agreed that step size adds complexity
@Taren If you want a step size other than 1, Iterator is the wrong tool for your task. Iterator can be made to do it, but it will be more awkward than other approaches, like Streams or just using an integer index and calling List.get.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.