Categories
collections java

Iterate list using streams in java

In this example, we will learn about iterate list using streams in java with example
It was introduced on Java 8

Features of Streams
  • No Storage
  • we can do arithmetic operations
  • we can filter the data without removing.
Syntax
list.stream().forEach((x) -> {operations});
Example
import java.util.ArrayList;
import java.util.List;

public class IterateListUsingStreams {

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Apple");
        list.add("Pineapple");
        list.add("Papaya");
        list.stream().forEach((x) -> System.out.println(x));
    }

}
Output
Apple
Pineapple
Papaya
Example with Pojo
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;
	}

}
IterateListUsingStreams2 .java
import java.util.ArrayList;
import java.util.List;

public class IterateListUsingStreams2 {

	public static void main(String[] args) {

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

		student = new Student();
		student.setId(1);
		student.setName("Rajesh");
		student.setAddress("Chennai");
		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("Student Id is "+x.getId()+" Name is "+x.getName()));

	}

}
Output
Student Id is 1 Name is Rajesh
Student Id is 1 Name is Kumar
References

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

GitHub

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

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

Related Articles

iterate stream with index in Java8

ArrayList in java with example

Leave a Reply

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