Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform action inside stream of operation in Java 8

I have a requirement to get the count of employees where employee name contains "kumar" and age is greater than 26. I am using Java 8 streams to iterate over the collection and I'm able to find employee count with above said condition.

But, in the meantime, I need to print the employee details.

Here's my code using Java 8 streams:

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);
}

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);
}

Whatever I am printing in the traditional way, I want to achieve the same using streams also.

How do I print a message within each iteration when using streams?

like image 551
Krishna Avatar asked Aug 20 '15 13:08

Krishna


2 Answers

You could use the Stream.peek(action) method to log info about each object of 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 performing an action on each element from the stream as they are consumed. The action must conform to the Consumer interface: take a single parameter t of type T (type of the stream element) and return void.

like image 104
Tunaki Avatar answered Oct 05 '22 08:10

Tunaki


Rather unclear, what you actually want, but this might help:
Lambdas (like your Predicate) can be written in two ways:
Without brackets like this: e -> e.getAge() > 26 or

...filter(e -> {
              //do whatever you want to do with e here 

              return e -> e.getAge() > 26;
          })...
like image 20
Paul Avatar answered Oct 05 '22 07:10

Paul