Skip to main content


Showing posts with the label Java 8 features

Java 8 - Iterating collections and maps with #forEach, Consumer and BiConsumer

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 . getEmplo

Java 8 - Filtering with Predicates

In this post, we will cover following items. What is java.util.function.Predicate? How to filter data with Predicates? Predicate chaining. Java 8 introduced many new features like Streaming API, Lambdas , Functional interfaces , default methods in interfaces and many more. Today, we will discuss about Predicate interface added in java.util.function package and its usage in filtering in-memory data. What is java.util.function.Predicate? Predicate is like a condition checker, which accepts one argument of type T and return the boolean value. It's a functional interface with functional method test(Object) . Here, Object is typed. @FunctionalInterface interface Predicate < T > { public boolean test ( T t ); } How we can filter data with Predicates? Consider we have Collection of employees and we want to filter them based on age, sex, salary and/ or with any other combinations. We can do that with Predicate . Let's understand this with one short