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

我的代码:

List 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会阻止边界问题吗?

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

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

所以上面的代码等于这个

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

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

如果你尝试过

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

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

你应该能够做到(不需要接听电话)

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

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

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

相当于

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

注意减1的保留。


回应评论:

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

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

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

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

因此:

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

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

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


这段代码:

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

相当于:

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

你的例子并不等同。