for loop using lambda expression in JAVA

后端 未结 3 1586
北荒
北荒 2020-12-20 16:39

My Code:

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


        
3条回答
  •  情话喂你
    2020-12-20 17:15

    List indexes in Java are 0-based.

    Therefore:

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

    You're calling ints.get(i-1) for each "i" where "i" is equal to the value of each element in the list "ints".

    If you were to call ints.get(i) you'd be fetching elements with indices equal to 1,2,3,4 and 5 and 5 wouldn't be a valid index into a list with 5 elements.


    This code:

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

    is equivalent to:

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

    Your examples aren't equivalent.

提交回复
热议问题