Java Lambda - Consumer example








Consumer interface represents an operation that accepts a single input argument and returns no result.

Method

  1. Consumer accept
  2. Consumer andThen

Example

The following example shows how to use Consumer.

import java.util.function.Consumer;

public class Main {
  public static void main(String[] args) {
    Consumer<String> c = (x) -> System.out.println(x.toLowerCase());
    c.accept("Java2s.com");
  }
}

The code above generates the following result.





Example 2

The following code shows how to create consumer with block statement.

import java.util.function.Consumer;
/*from  w  w  w  . ja  v a 2s  .co m*/

public class Main {
    public static void main(String[] args) {
      int x = 99;
      
      Consumer<Integer> myConsumer = (y) -> 
      {
          System.out.println("x = " + x); // Statement A
          System.out.println("y = " + y);
      };

      myConsumer.accept(x);
    }
}

The code above generates the following result.





Example 3

The following code shows how to pass Consumer as parameter.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/*  w  w w .j a va2s  . c  o  m*/
public class Main {
   public static void main(String[] args) {
      List<Student> students = Arrays.asList(
            new Student("John", 3),
            new Student("Mark", 4)
      );

      acceptAllEmployee(students, e -> System.out.println(e.name));
      acceptAllEmployee(students, e -> {
         e.gpa *= 1.5;
      });
      acceptAllEmployee(students, e -> System.out.println(e.name + ": " + e.gpa));
   }

   public static void acceptAllEmployee(List<Student> student, Consumer<Student> printer) {
      for (Student e : student) {
         printer.accept(e);
      }
   }

}
class Student {
  public String name;
  public double gpa;

  Student(String name, double g) {
    this.name = name;
    this.gpa = g;
  }
}

The code above generates the following result.