如何遍历列表并在到达末尾时回到第一个元素?

huangapple go评论73阅读模式
英文:

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

问题

我有一个对象列表。我想用ListIterator遍历它们,但是如果到达末尾,我希望.next()返回第一个元素,并继续再次遍历列表。这可能吗?

ListIterator<Post> postsIterator = posts.listIterator(); // posts只有3个元素
for (int i = 0; i < 15; i++) {
  System.out.println(postsIterator.next().getText());
}
英文:

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&lt;Post&gt; postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i &lt; 15; i++)
{
  System.out.println(postsIterator.next().getText());
}

答案1

得分: 5

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

for (int i = 0; i < 15; i++) {
    it = it.hasNext() ? it : it.listIterator();
    System.out.println(it.next().getText());
}
英文:
ListIterator&lt;Post&gt; it = posts.listIterator();

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

答案2

得分: 3

你可以使用一些流操作的魔法来创建一个实际上永远不会结束的迭代器:

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());
}

如果你有 Guava 库可用,有一个方法 Iterators.cycle(Iterable) 可以实现你想要的功能。

也许一个稍微更简单的方法是完全避免使用迭代器:

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

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

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

List&lt;String&gt; strings = Arrays.asList(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;);

Iterator&lt;String&gt; it = Stream.generate(() -&gt; strings).flatMap(List::stream).iterator();
for (int i = 0; i &lt; 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&lt;String&gt; strings = Arrays.asList(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;);

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

答案3

得分: 2

需要在到达末尾时将 ListIterator 重置到索引 0 处。

演示:

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");
        }
    }
}

输出:

A    B    C    A    B    C    A    B    C    A    B    C    A    B    C    
英文:

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&lt;String&gt; list = List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);
		ListIterator&lt;String&gt; itr = list.listIterator();

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

Output:

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

答案4

得分: 2

为什么不简单地追踪你的迭代变量呢?像这样:

ListIterator<Post> postsIterator = posts.listIterator(); // posts只有3个元素
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; // 为了确保增量变为0
    }
}

如果你坚持要有一个硬编码的阈值 15,那么:

ListIterator<Post> postsIterator = posts.listIterator(); // posts只有3个元素
for (int i = 0; i < 15; i++) {
    if (!postsIterator.hasNext()) postsIterator = posts.listIterator();
    Post post = postsIterator.next();
    System.out.println(post == null ? "" : post.getText());
}
英文:

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

ListIterator&lt;Post&gt; postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i &lt; posts.size(); i++) {
    if (!postsIterator.hasNext()) break;
    Post post = postsIterator.next();
    System.out.println(post==null ? &quot;&quot; : 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&lt;Post&gt; postsIterator = posts.listIterator(); //posts only has 3 elements
for (int i = 0; i &lt; 15; i++) {
    if (!postsIterator.hasNext()) postsIterator = posts.listIterator();
    Post post = postsIterator.next();
    System.out.println(post==null ? &quot;&quot; : post.getText());
}

huangapple
  • 本文由 发表于 2020年9月26日 05:34:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64071577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定