lamda循环_for循环在JAVA中使用lambda表达式

本文探讨了在Java中使用Lambda表达式替代for循环的情况,通过例子解释了为何在forEach中需要使用`i-1`以及其与传统for循环的不同。强调Lambda表达式本质上是函数,提供的是循环内的行为,而forEach方法提供了循环结构。
摘要由CSDN通过智能技术生成

My Code:

List 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

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

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

解决方案

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.

If you tried with

List ints = Stream.of(10,20,40,30,50).collect(Collectors.toList());

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值