Java 8 streams filter

package com.test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Customer {

private String firstName;

private String lastName;

private int orderNo;

public Customer(String firstName, String lastName, int orderNo) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.orderNo = orderNo;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getOrderNo() {
return orderNo;
}

public void setOrderNo(int orderNo) {
this.orderNo = orderNo;
}

public static void main(String[] args) {
List customers=new ArrayList();
customers.add(new Customer(“garima”,”pandey”,1));
customers.add(new Customer(“ashu”,”dikshit”,2));
customers.add(new Customer(“gaurav”,”dixit”,3));

//1)Filter and foreach
//The following basically streams the collection and on a stream you can have multiple operations performed
//The stream has three parts, first is the source which in our case is customers collection, second part is all the operations that need to be performed on that stream, so below is a filter operation that is performed on the stream and finally we have a terminal operation that is the end condition, below for each is the end condition

customers.stream().filter(c->c.getLastName().startsWith("d")).forEach(c->System.out.println(c.getFirstName()));// output-->ashu,gaurav

//2)Filter and collect
//stream.filter() lets you to filter a list and collect() to convert stream into a list.

List collected=customers.stream().filter(c->c.getFirstName().startsWith("g")).collect(Collectors.toList());
collected.forEach(c->System.out.println(c.getFirstName()));//output-->garima,gaurav

//3)filter and .findAny().orElse(null)

Customer cust=customers.stream().filter(c->c.getFirstName().contains("garima")).findAny().orElse(null);
System.out.println(cust.getFirstName());//output-->garima

//4)filter and .findAny().orElse(null)

Customer custNull=customers.stream().filter(c->c.getFirstName().contains("test")).findAny().orElse(null);
System.out.println(custNull);//output-->null

//5)filter and map
//map function can be used to perform some operation on all of it’s elements.

customers.stream().filter(c->c.getFirstName().startsWith("g")).map(Customer::getFirstName).collect(Collectors.toList()).forEach(System.out::println);//output->garima,gaurav

}
}

Advertisements