Jack Johnson
Jack Johnson

Reputation: 1525

How do you iterate through a List and go back to the first element if it reaches the end?

So I have a List of objects. I want to iterate through them with a ListIterator but I want the .next() to return the first element if it reaches the end and keep iterating through the list again. Is that possible?

ListIterator<Post> postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i < 15; i++)
{
  System.out.println(postsIterator.next().getText());
}

Upvotes: 1

Views: 1573

Answers (4)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11120

Why not to simply track your iteration variable? like this:

ListIterator<Post> postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i < posts.size(); i++) {
    if (!postsIterator.hasNext()) break;
    Post post = postsIterator.next();
    System.out.println(post==null ? "" : post.getText());
    if (i==posts.size()-1) {
        i=-1; //to make sure that increment gets to 0
    }
}

If you insist you want to have a hardcoded threshold 15, then:

ListIterator<Post> postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i < 15; i++) {
    if (!postsIterator.hasNext()) postsIterator = posts.listIterator();
    Post post = postsIterator.next();
    System.out.println(post==null ? "" : post.getText());
}

Upvotes: 2

clstrfsck
clstrfsck

Reputation: 14829

You could use some stream magic to create an iterator that actually goes on for ever:

List<String> strings = Arrays.asList("one", "two", "three");

Iterator<String> it = Stream.generate(() -> strings).flatMap(List::stream).iterator();
for (int i = 0; i < 15; ++i) {
    System.out.println(it.next());
}

If you have Guava available, there is a method Iterators.cycle(Iterable) that does what you want.

Maybe a slightly easier way would be to avoid using an iterator altogether:

List<String> strings = Arrays.asList("one", "two", "three");

for (int i = 0; i < 15; ++i) {
    System.out.println(strings.get(i % strings.size()));
}

Upvotes: 3

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

You need to reset the ListIterator to the index, 0 once it reaches at the end.

Demo:

import java.util.List;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("A", "B", "C");
        ListIterator<String> itr = list.listIterator();

        for (int i = 0; i < 15; i++) {
            if (!itr.hasNext()) {
                itr = list.listIterator();
            }
            System.out.print(itr.next() + "\t");
        }
    }
}

Output:

 A  B   C   A   B   C   A   B   C   A   B   C   A   B   C   

Upvotes: 2

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

ListIterator<Post> it = posts.listIterator();

for (int i = 0; i < 15; i++) {
    it = it.hasNext() ? it : it.listIterator();
    System.out.println(it.next().getText());
}

Upvotes: 5

Related Questions