Search code examples
javafor-loopiterationprimitive-typeslistiterator

Enhanced loop for primitives


Is there any short enhanced form of for loop which we can use for primitives. I have do the legacy code for looping on to primitives, like this

for(int i=0; i<10; i++){
}

Although for objects, we have ehanced for loop like

for(MyObject m : myObjectList){
}

Is there any similar option for primitives also?


Solution

  • Found the solution, IntStreams in java 8 can replace the regular for-loop utilizing IntStream.range()

    IntStream.range(1, 4)
    .forEach(System.out::println);