在JAVA中使用lambda表达式的for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24399181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:59:43  来源:igfitidea点击:

for loop using lambda expression in JAVA

javaforeachlambdajava-8

提问by Kick Buttowski

My Code:

我的代码:

List<Integer> ints = Stream.of(1,2,4,3,5).collect(Collectors.toList());
ints.forEach((i)-> System.out.print(ints.get(i-1)+ " "));

out put:

输出:

1 2 3 4 5

1 2 3 4 5

my question is why i must be i-1 inside the get method? does i-1 prevent the out of boundary issue?

我的问题是为什么在 get 方法中我必须是 i-1?i-1 是否可以防止越界问题?

Does below code acts like the for loop iteration?

下面的代码是否像 for 循环迭代?

(i)-> System.out.print(ints.get(i-1))

so is above code equal to this

所以上面的代码等于这个

for(Ineger i:ints)
   System.out.print(ints.get(i));

采纳答案by vossad01

The lambda parameter itakes the value of the items in the collection, not the indexes. You are subtracting 1because the values happen to be one greater than their index.

lambda 参数i采用集合中项目的值,而不是索引。您正在减去,1因为这些值恰好比它们的索引大 1。

If you tried with

如果你试过

List<Integer> ints = Stream.of(10,20,40,30,50).collect(Collectors.toList());
ints.forEach((i)-> System.out.print(ints.get(i-1)+ " "));

You would find the code does not work so well.

你会发现代码不能很好地工作。

You should be able to simply do (not needing to do a getcall)

你应该能够简单地做(不需要get打电话)

ints.forEach((i)-> System.out.print(i + " "));


Your lambda and your proposed for loop are not equivalent.

您的 lambda 和您建议的 for 循环并不等效。

ints.forEach((i)-> System.out.print(ints.get(i-1)))

Would be equivalent to

将相当于

for(Integer i:ints)
   System.out.print(ints.get(i-1));

Note the preservation of the minus 1.

注意负 1 的保留。



In response to the comment:

回应评论:

Lambdas are not loops, they are functions (effectively anyway). In your first example the forEachmethod is what provides the looping functionality. The argument lambda is what it should doon each iteration. This is equivalent to the bodyof your for loop

Lambda 不是循环,它们是函数(无论如何都是有效的)。在您的第一个示例中,该forEach方法提供了循环功能。参数 lambda 是它在每次迭代中应该做的事情。这相当于身体的for循环

In the example in the comment, maxis the function that provides the loop like behavior. It will iterate (do a loop) of the items to find the maximum value). The lambda you provide i -> iwould be an identity function. It takes one parameter and returns that object unmodified.

在注释中的示例中,max是提供类似循环行为的函数。它将迭代(循环)项目以找到最大值)。您提供的 lambdai -> i将是一个身份函数。它接受一个参数并返回未修改的对象。

Suppose you had a more complex object and you wanted to compare them on a particular member such as GetHighScore(). Then you could use i -> i.GetHighScore()to get the object with the highest score.

假设您有一个更复杂的对象,并且您想在特定成员上比较它们,例如GetHighScore(). 然后你可以用i -> i.GetHighScore()来获得最高分的对象。

回答by Matt Coubrough

List indexes in Java are 0-based.

Java 中的列表索引是从 0 开始的。

Therefore:

所以:

ints.get(0) == 1;
ints.get(1) == 2;
ints.get(2) == 3;
//etc...

You're calling ints.get(i-1) for each "i" where "i" is equal to the valueof each element in the list "ints".

您正在为每个“i”调用 ints.get(i-1),其中“i”等于列表“ints”中每个元素的

If you were to call ints.get(i)you'd be fetching elements with indicesequal to 1,2,3,4 and 5 and 5 wouldn't be a valid index into a list with 5 elements.

如果您要调用,ints.get(i)您将获取索引等于 1、2、3、4 和 5 的元素,而 5 和 5 将不是具有 5 个元素的列表的有效索引。



Thiscode:

这段代码:

ints.forEach((i)-> System.out.print(ints.get(i-1)+ " "));

is equivalent to:

相当于:

for(int i : ints ) {
    System.out.print(ints.get(i-1) + " ");
}

Your examples aren't equivalent.

你的例子是不等价的。

回答by user3646774

This is a wish, rather than a solution! Other language like NodeJS/JavaScript have a similar loop that passes two arguments to the lambda. Parameter i is the index and parameter j is the item from the container (regarless of container type).

这是一个愿望,而不是一个解决方案!其他语言如 NodeJS/JavaScript 有一个类似的循环,将两个参数传递给 lambda。参数 i 是索引,参数 j 是容器中的项目(无论容器类型如何)。

ints.forEach((i,j)-> System.out.print("Index is ${i} and item is ${j}", i, j));

ints.forEach((i,j)-> System.out.print("Index is ${i} and item is ${j}", i, j));