Categories
collections java

filter operations in streams on java 

In this example we learn filter operations in streams on java 

In Java 8 it is easy to filter record from an arraylist

Streams API providing powerful features to filter an record from a list without modifying it

This will returns a stream consisting of the elements of this stream that match the given predicate.

Syntax
Stream filter(Predicate<? super T> predicate)<br><br>
list.stream().filter({operations});
Example
import java.util.ArrayList;
import java.util.List;

public class FilterExample {

	public static void main(String[] args) {

		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().filter(x -> x.getName().equals("Rajesh"))
		.forEach(x -> System.out.print(x.getAddress()));

	}

}
Person.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
Mumbai
Reference

oracle docs

Related Articles

Iterate list using streams in java

iterate stream with index in Java8

Leave a Reply

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