gpt4 book ai didi

java - 需要时一一获取集合元素

转载 作者:行者123 更新时间:2023-12-02 10:57:52 24 4
gpt4 key购买 nike

我有一个 Game 类,其中包含一个 Board 类,其中包含一个 Rows ArrayList。

当前游戏可以 getCurrentRow(),当游戏进行时,它会执行 getNextRow()。 Board 获取 currentRow,从错误的一端循环遍历 ArrayList,并在每一步中将该行保存在 lastCheckedRow 中,并在找到 currentRow 时中断。 nextRow 将成为lastCheckedRow。足够简单,但丑陋。

我想将这种方法改为流。是否可以创建一个保持可访问的流,在调用时一次仅返回一个元素?

public class Board implements Skinnable{

private Stream<Skinnable> stream;

protected List<Skinnable> rowItems = new ArrayList<>();

private BoardRow currentRow;

private final BoardSkin skin;

public Board(Game game) {

for (int i = 0; i < 10; i++) {
rowItems.add(new BoardRow(game));
if (i == 9) {
setCurrentRow((BoardRow) rowItems.get(rowItems.size() - 1));
}
}

stream = rowItems.stream();
skin = new BoardSkin(this);
}

public void setCurrentRow(BoardRow row) {
currentRow = row;
currentRow.activate();
}

public Row getStreamedRowItem () {

List<Skinnable> collect = stream.limit(1).collect(Collectors.toList());

return (Row) collect.get(0);
}
}

这一次有效,然后流被关闭。这是一个更普遍的问题。我在这里和其他地方都进行了搜索,但这对我来说太新了,所以我什至无法正确表达我的问题,因此我陷入了困境。

最佳答案

流只能遍历一次。因此,您无法在保持其打开的情况下运行 .collect 终端操作。

一次检索元素的最佳替代方法是使用迭代器:

private Iterator<Skinnable> stream; //Please rename the variable

然后在构造函数中创建迭代器:

stream = rowItems.iterator();

检索下一个元素更改为:

public Row getStreamedRowItem () {

//you'll need to check if there's a next element
//if(stream.hasNext())
return stream.next();
}

关于java - 需要时一一获取集合元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51578612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com