Java 8 Streams filter() - Simple Example

#JavaInspires



😀 Hi Guys,

Welcome to Java Inspires.

Java 8 Streams - Simple Example

In this example, we will see how to use filter method from Java 8 streams.

Here, we will create a employee list and filter the same with employee age greaterthan 30.

Java8Example.java

package com.javainspires.java8example;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * 
 * @author Java Inspires
 *
 */
public class Java8Example {

	public static void main(String[] args) {

		// create employee list
		List<Employee> employees = new ArrayList<Employee>();
		// add employees to the list
		employees.add(new Employee("E101", "John", 22));
		employees.add(new Employee("E102", "Steve", 28));
		employees.add(new Employee("E103", "William", 37));
		employees.add(new Employee("E104", "Clark", 32));
		employees.add(new Employee("E105", "Kent", 33));

		// now we will filter this employee list where employees having age greater than
		// 30
		// we do this using filter from stream

		// convert list to stream
		Stream<Employee> empStream = employees.stream().filter(e -> (e.getAge() > 30)); // this result one more stream

		System.out.println("Employees With Age > 30");
		empStream.forEach(e -> System.out.println(e.getName()));
	}

}

// create Employee class
class Employee {

	private String id;
	private String name;
	private int age;

	public Employee(String id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

Output:

Employees With Age > 30
William
Clark
Kent




#JavaInspires

Post a Comment

Previous Post Next Post