What is wrong in my approach to create a List of Integers using IntStream and forEach?

  • A+
Category:Languages

The naive code I have is:

class ${     public static void main(String[] _) {         final List<Integer> ints = new ArrayList<>();         IntStream.iterate(0, i -> i++).limit(5).forEach(val -> ints.add(val));         System.out.println(ints);     } } 

where my expectation was to see the following in the console:

[0, 1, 2, 3, 4]  

but the actual is:

[0, 0, 0, 0, 0] 

Probably something very simple but what am I missing?

 


You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++

final List<Integer> ints = new ArrayList<>(); IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val)); System.out.println(ints); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: