Performing actions inside a workflow in Java 8

I have a requirement to get the number of employees in which the employee name contains β€œkumar” and the age is greater than 26. I use Java 8 threads to iterate through the collection, and I can find the employee counter with the above state.

But at the same time, I need to print out employee data.

Here is my code using Java 8 threads:

public static void main(String[] args) { List<Employee> empList = new ArrayList<>(); empList.add(new Employee("john kumar", 25)); empList.add(new Employee("raja", 28)); empList.add(new Employee("hari kumar", 30)); long count = empList.stream().filter(e -> e.getName().contains("kumar")) .filter(e -> e.getAge() > 26).count(); System.out.println(count); } 

The traditional way:

 public static void main(String[] args){ List<Employee> empList = new ArrayList<>(); empList.add(new Employee("john kumar", 25)); empList.add(new Employee("raja", 28)); empList.add(new Employee("hari kumar", 30)); int count = 0; for (Employee employee : empList) { if(employee.getName().contains("kumar")){ if(employee.getAge() > 26) { System.out.println("emp details :: " + employee.toString()); count++; } } } System.out.println(count); } 

No matter what I print in the traditional way, I want to achieve the same use of streams.

How to print a message in each iteration when using streams?

+7
java java-8 java-stream
source share
2 answers

You can use the Stream.peek(action) method to record information about each object in your stream:

 long count = empList.stream().filter(e -> e.getName().contains("kumar")) .filter(e -> e.getAge() > 26) .peek(System.out::println) .count(); 

The peek method allows you to perform an action for each element in the stream as it is consumed. The action should match the Consumer interface: take a single parameter t type t (type of stream element) and return void .

+14
source share

It's rather unclear what you really want, but this may help:
Lambdas (e.g. your Predicate ) can be written in two ways:
Without brackets: e -> e.getAge() > 26 or

 ...filter(e -> { //do whatever you want to do with e here return e -> e.getAge() > 26; })... 
+2
source share

All Articles