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?
java java-8 java-stream
Krishna
source share