3.3.  Filter a collection by using lambda expressions

[Note]
  • blah

The Stream.filter(...) methods is an intermediate operation. It filters a stream on the basis of a given predicate and returns a stream object. And again you can apply other stream methods to this instance. The method syntax is as follows:


Stream<T> filter(Predicate<? super T> predicate)

					

You pass a Predicate as an argument on the basis of which filter(...) method filters the stream and returns a new Stream object.

In the example below we have an Employee list and created a Predicate. This predicate will be passed to filter as an argument. Finally we will print the filtered stream:

public class Employee {
    public String name;
    public double salary;
    public Employee(String n, double s) {
        name = n; salary = s;
    }
    public String toString() { return name + " : " + salary; }
}
					


List<Employee> emps = new ArrayList<>();
emps.add(new Employee("John", 120000.0));
emps.add(new Employee("Daniel", 112000.0));
emps.add(new Employee("Dzmitry", 36000.0));
emps.add(new Employee("Steven", 150000.0));
Predicate<Employee> p = emp -> emp.salary > 100000.0;
Consumer<Employee> c = emp -> System.out.println(emp);
emps.stream().filter(p).forEach(c);

					

the output is as follows:

John : 120000.0
Daniel : 112000.0
Steven : 150000.0
					

You can filter a Stream with more than one condition by chaining filter(...) methods:


List<Employee> emps = ...
...
Predicate<Employee> p1 = emp -> emp.salary > 100000.0;
Predicate<Employee> p2 = emp -> emp.salary < 150000.0;
Consumer<Employee> c = emp -> System.out.println(emp);
emps.stream().filter(p1).filter(p2).forEach(c);

					

the output is:

John : 120000.0
Daniel : 112000.0
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz