Krishna
Krishna

Reputation: 198

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?

Upvotes: 8

Views: 12358

Answers (2)

Tunaki
Tunaki

Reputation: 137229

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.

Upvotes: 23

user4668606
user4668606

Reputation:

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

Upvotes: 2

Related Questions