Saturday 15 August 2015

Streams: Searching and finding

Streams api provides following methods to search and find elements of a stream.

Method
Argument
Return type
Description
anyMatch
Predicate
boolean
Returns true, if any element of the stream matches given predicate, else false.
allMatch
Predicate
boolean
Returns true if the stream is empty (or) all the elements of the stream matches to given predicate, else false.
noneMatch
Predicate
boolean
It is opposite of allMatch function. Returns true, if stream is empty (or) no element in the stream matches to given predicate, else false.
findAny
No arguments
Optional
Returns an Optional that describes some element of the stream. If stream is empty, it returns empty optional.
findFirst
No arguments
Optional
Returns an Optional that describes first element of the stream. If stream is empty, it returns empty optional.

Note:
Functions anyMatch, allMatch, noneMatch use short circuit operators (&&, ||).

1. Check whether any employee exist in stream, where salary > 100000
employees.stream().anyMatch((emp) -> emp.getSalary()>100000)

2. Check whether any employee exist in stream, where salary > 1000
employees.stream().anyMatch((emp) -> emp.getSalary()<10000)

3. Check whether all employees are getting salary > 25000.
employees.stream().allMatch((emp) -> emp.getSalary()>25000)

As I said, noneMatch is opposite to allMatch function, You can write same using noneMatch like following.

4. Find any employee whose salary > 100000.
employees.stream().filter((emp)->emp.getSalary()>100000).findAny()

5. Find first employee (In ascending order of salary), whose salary > 100000.
employees.stream().filter((emp) -> emp.getSalary() > 100000).sorted(comparing(Employee::getSalary)).findFirst();


Find the complete application below.
import java.util.Objects;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private int age;
 private String city;
 private double salary;

 public Employee(int id, String firstName, String lastName, int age,
   String city, double salary) {
  super();
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.city = city;
  this.salary = salary;
 }

 public int getId() {
  return id;
 }

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

 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 getAge() {
  return age;
 }

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

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public double getSalary() {
  return salary;
 }

 public void setSalary(double salary) {
  this.salary = salary;
 }

 @Override
 public boolean equals(Object employee) {
  if (Objects.isNull(employee))
   return false;

  if (!(employee instanceof Employee))
   return false;

  Employee emp = (Employee) employee;

  return id == emp.id;
 }

 @Override
 public int hashCode() {
  return Objects.hash(id, firstName, lastName, age);
 }

 @Override
 public String toString() {
  return String.format("%s(%s,%d,%f)", firstName, city, age, salary);
 }

}

import static java.util.Comparator.comparing;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Test {
 public static List<Employee> getEmployees() {
  Employee emp1 = new Employee(1, "Hari Krishna", "Gurram", 26,
    "Bangalore", 40000);
  Employee emp2 = new Employee(2, "Joel", "Chelli", 27, "Hyderabad",
    50000);
  Employee emp3 = new Employee(3, "Shanmukh", "Kummary", 28, "Chennai",
    35000);
  Employee emp4 = new Employee(4, "Harika", "Raghuram", 27, "Chennai",
    76000);
  Employee emp5 = new Employee(5, "Sudheer", "Ganji", 27, "Bangalore",
    90000);
  Employee emp6 = new Employee(6, "Rama Krishna", "Gurram", 27,
    "Bangalore", 56700);
  Employee emp7 = new Employee(7, "PTR", "PTR", 27, "Hyderabad", 123456);
  Employee emp8 = new Employee(8, "Siva krishna", "Ponnam", 28,
    "Hyderabad", 98765);
  Employee emp9 = new Employee(9, "Raju", "Antony", 40, "Trivendram",
    198765);

  Employee emp10 = new Employee(10, "Brijesh", "Krishnan", 34,
    "Trivendram", 100000);
  Employee emp11 = new Employee(9, "Raju", "Antony", 40, "Trivendram",
    198765);

  Employee emp12 = new Employee(10, "Brijesh", "Krishnan", 34,
    "Trivendram", 100000);

  List<Employee> employees = new ArrayList<>();

  employees.add(emp1);
  employees.add(emp2);
  employees.add(emp3);
  employees.add(emp4);
  employees.add(emp5);
  employees.add(emp6);
  employees.add(emp7);
  employees.add(emp8);
  employees.add(emp9);
  employees.add(emp10);
  employees.add(emp11);
  employees.add(emp12);

  return employees;
 }

 public static void main(String args[]) {
  List<Employee> employees = getEmployees();

  /* Check whether any employee exist in stream, where salary > 100000 */
  boolean result = employees.stream().anyMatch(
    (emp) -> emp.getSalary() > 100000);
  System.out.println(result);

  /* Check whether any employee exist in stream, where salary < 10000 */
  result = employees.stream().anyMatch((emp) -> emp.getSalary() < 10000);
  System.out.println(result);

  /* Check whether all employees are getting salary > 25000 */
  result = employees.stream().allMatch((emp) -> emp.getSalary() > 25000);
  System.out.println(result);

  /*
   * Check whether all employees are getting salary > 25000 using
   * noneMatch function
   */
  result = employees.stream()
    .noneMatch((emp) -> emp.getSalary() <= 25000);
  System.out.println(result);

  /* Find any employee whose salary > 100000 */
  Optional<Employee> oneEmp = employees.stream()
    .filter((emp) -> emp.getSalary() > 100000).findAny();
  System.out.println(oneEmp.get());

  /*
   * Find first employee (In ascending order of salary), whose salary >
   * 100000.
   */
  oneEmp = employees.stream().filter((emp) -> emp.getSalary() > 100000)
    .sorted(comparing(Employee::getSalary)).findFirst();
  System.out.println(oneEmp.get());

 }
}


Output

true
false
true
true
PTR(Hyderabad,27,123456.000000)
PTR(Hyderabad,27,123456.000000)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment