有没有一种简洁的方法来迭代流,同时有权访问流中的索引?
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List<String> nameList;
Stream<Integer> indices = intRange(1, names.length).boxed();
nameList = zip(indices, stream(names), SimpleEntry::new)
.filter(e -> e.getValue().length() <= e.getKey())
.map(Entry::getValue)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
与那里给出的LINQ示例相比,这似乎相当令人失望
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
Run Code Online (Sandbox Code Playgroud)
有更简洁的方法吗?
此外,看起来拉链已移动或被移除......
有没有办法forEach
在Java 8中构建一个使用索引进行迭代的方法?理想情况下,我喜欢这样的事情:
params.forEach((idx, e) -> query.bind(idx, e));
Run Code Online (Sandbox Code Playgroud)
我现在能做的最好的事情是:
int idx = 0;
params.forEach(e -> {
query.bind(idx, e);
idx++;
});
Run Code Online (Sandbox Code Playgroud) 基于BlackJack问题,我想知道如何表明所有获胜的手牌.实际上,原始问题只是简单地询问了两个不大于21的数字.所以这样的方法就像
public int blackjack(int a, int b);
Run Code Online (Sandbox Code Playgroud)
但是,如果有人希望返回所有获胜的牌(假设输入数组中的位置是桌子上的座位),那么签名如下:
/**
* returns an array indicate the index in the specified hands that
* correspond to the winning locations. Will return an empty array if
* there are no winners. The length of the returned array is how many
* winning hands there were
* @param hands The total for each hand, where the index is the seat
* @return the index/"seat" where a winning hand was found; may return …
Run Code Online (Sandbox Code Playgroud) 在这个方法中,我试图找到一个第一个偶数整数ArrayList
(供进一步使用).
但是,当我调用方法时,我得到-1.据我所知,这意味着列表中没有整数(但确实存在).
这是代码:
public static int rangeBetweenEvens(ArrayList<Integer> list) {
int firstEven = 0;
for (int i = 0; i < list.size(); i++)
{
firstEven = list.indexOf((i) % 2 == 0);
}
return firstEven;
}
Run Code Online (Sandbox Code Playgroud)