Showing posts with label java.util.function package. Show all posts

Iterating Collections API

Java 8 introduced new way of iterating Collections API. It is retrofitted to support #forEach method which accepts Consumer in case of Collection and BiConsumer in case of Map.

Consumer

Java 8 added introduced new package java.util.function which also includes Consumer interface. It represents the operation which accepts one argument and returns no result.

Before Java 8, you would have used for loop, extended for loop and/ or Iterator to iterate over Collections .

List<Employee> employees = EmployeeStub.getEmployees();
Iterator<Employee> employeeItr = employees.iterator();
Employee employee;
while (employeeItr.hasNext()) {
  employee = employeeItr.next();
  System.out.println(employee);
}

In Java 8, you can write Consumer and pass the reference to #forEach method for performing operation on every item of Collection.

// fetch employees from Stub
List<Employee> employees = EmployeeStub.getEmployees();
// create a consumer on employee
Consumer<Employee> consolePrinter = System.out::println;
// use List's retrofitted method for iteration on employees and consume it
employees.forEach(consolePrinter);

Or Just one liner as

employees.forEach(System.out::println);

Before Java 8, you would have iterated Map as

Map<Long, Employee> idToEmployeeMap = EmployeeStub.getEmployeeAsMap();
for (Map.Entry<Long, Employee> entry : idToEmployeeMap.entrySet()) {
  System.out.println(entry.getKey() + " : " + entry.getValue());
}

In Java 8, you can write BiConsumer and pass the reference to #forEach method for performing operation on every item of Map.

BiConsumer<Long, Employee> employeeBiConsumer = (id, employee) -> System.out.println(id + " : " + employee);
Map<Long, Employee> idToEmployeeMap = EmployeeStub.getEmployeeAsMap();
idToEmployeeMap.forEach(employeeBiConsumer);

or Just a one liner:

idToEmployeeMap.forEach((id, employee) -> System.out.println(id + " : " + employee));

This is how we can benefit with newly introduced method for iteration. I hope you found this post informative. You can get the full example on Github.

java.util.function package

Java 8 introduced new package and introduced many functional interface. It can be divided into four categories.

  • Predicate
  • Consumer
  • Function
  • Supplier

Predicate

It represents a boolean-valued function of one argument. It is a functional interface with method test(T) where T is typed.

You can see the usage here.

Consumer

It represents an operation accept(s) argument(s) and return void with side-effects. Java 8 introduced many versions of Consumers.

You can see the usage of Consumer here.