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

Kic*_*ski 6 java foreach lambda java-8

我的代码:

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

出局:

1 2 3 4 5

我的问题是为什么我必须在get方法中使用i-1?i-1会阻止边界问题吗?

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

(i)-> System.out.print(ints.get(i-1))
Run Code Online (Sandbox Code Playgroud)

所以上面的代码等于这个

for(Ineger i:ints)
   System.out.print(ints.get(i));
Run Code Online (Sandbox Code Playgroud)

vos*_*d01 13

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

如果你试过

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

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

你应该能够做到(不需要get打电话)

ints.forEach((i)-> System.out.print(i + " "));
Run Code Online (Sandbox Code Playgroud)

你的lambda和你提出的for循环不等价.

ints.forEach((i)-> System.out.print(ints.get(i-1)))
Run Code Online (Sandbox Code Playgroud)

相当于

for(Integer i:ints)
   System.out.print(ints.get(i-1));
Run Code Online (Sandbox Code Playgroud)

注意减1的保留.


回应评论:

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

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

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