How to replace for loop with stream java

What you will learn here about java stream

  • How to replace for loop with stream java

Here we will see how to replace for loop with java stream API. In java we can replace for loop with forEach loop using stream which is shown below.
How to replace for loop with stream java

How to replace for loop with stream java

Sample program for replacing for loop with stream API in java is given below.

import java.util.ArrayList;
import java.util.List;

public class ForLoopWithStream {

	public static void main(String[] args) {
		List movies=new ArrayList<>();
		
		movies.add("Zero");movies.add("Sultan");
		movies.add("Tanhaji");movies.add("Robot");
		movies.add("Wanted");
		
		System.out.println("----------------old way of using for ----------------");
		for(int i=0;i<movies.size();i++)
		{
			System.out.println(movies.get(i));
		}
		
		System.out.println("----------------for loop with stream first way ----------------");
		movies.stream().forEach(System.out::println);
		
		System.out.println("----------------for loop with stream second way ----------------");
		movies.stream().forEach(movie->System.out.println(movie));
		
	}

}

OUTPUT

—————-old way of using for —————-
Zero
Sultan
Tanhaji
Robot
Wanted
—————-for loop with stream first way —————-
Zero
Sultan
Tanhaji
Robot
Wanted
—————-for loop with stream second way —————-
Zero
Sultan
Tanhaji
Robot
Wanted

You may also like...