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