在JAVA中使用lambda表达式的for循环 [英] for loop using lambda expression in JAVA

查看:208
本文介绍了在JAVA中使用lambda表达式的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

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

输出:

1 2 3 4 5

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

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

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

Does below code acts like the for loop iteration?

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

推荐答案

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

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

如果你尝试过

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.

您应该能够简单地执行(不需要执行 get 调用)

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

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

<小时>

您的 lambda 和您建议的 for 循环不等价.


Your lambda and your proposed for loop are not equivalent.

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

相当于

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

注意保留负 1.

回应评论:

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

Lambdas are not loops, they are functions (effectively anyway). In your first example the forEach method is what provides the looping functionality. The argument lambda is what it should do on each iteration. This is equivalent to the body of your for loop

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

In the example in the comment, max is 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 -> i would be an identity function. It takes one parameter and returns that object unmodified.

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

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.

这篇关于在JAVA中使用lambda表达式的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆