Categories
collections java

foreach in java8 using streams

In this tutorial, we will learn about foreach in java8 using streams

In java8, We can easily iterate a list using streams.

Streams API provided a lot of features. In this post, we are going to see about foreach

Syntax
stream().forEach({operations});
Example

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

public class ForEachExample {

	public static void main(String[] args) {
		try {

			List studentList = new ArrayList();
			Student student = null;

			student = new Student();
			student.setId(1);
			student.setName("Rajesh");
			student.setAddress("Mumbai");
			studentList.add(student);

			student = new Student();
			student.setId(1);
			student.setName("Kumar");
			student.setAddress("Chennai");
			studentList.add(student);

			studentList.stream()
					.forEach(x -> System.out.println("Name is " + x.getName() + " Address is " + x.getAddress()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Student.java

public class Student {

	private int id;
	private String name;
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
Output
Name is Rajesh Address is Mumbai
Name is Kumar Address is Chennai
Related Article

sorting operations in java using streams

Iterate list using streams in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ForEachExampleUsingStreams.java

Leave a Reply

Your email address will not be published. Required fields are marked *