如何在Java的lambda表达式中使用Consumer和BiConsumer接口?

Consumer 接口是一个预定义的函数接口,可以在创建 lambda 表达式或方法引用时使用。此接口表示接受单个输入参数且不返回任何内容的操作。它只包含一个名为 accept ()的方法。BiConsumer 接口类似于 Consumer 接口,接受两个输入参数,不返回任何内容。

语法

@FunctionalInterface
public interface Consumer<T>@FunctionalInterface
public interface BiConsumer<T, U>

示例

import java.util.*;
import java.util.function.*;

public class ConsumerBiConsumerTest {
   public static void main(String[] args) {
      Consumer<String> c = (x) -> System.out.println(x.toLowerCase());  // lambda 表达式
      c.accept("Raja");
 
      Consumer<Integer> con = (x) -> {  // lambda 表达式
      System.out.println(x + 10);
         System.out.println(x - 10);
      };
      con.accept(10);

      BiConsumer<Strng, String> bc = (x, y) -> { System.out.println(x + y);};
      bc.accept("1", "2");

      List<Person> plist = Arrays.asList(new Person("RAJA"), new Person("ADITHYA"));
      acceptAllEmployee(plist, p -> System.out.println(p.name));
      acceptAllEmployee(plist, p -> {p.name = "unknown";});
      acceptAllEmployee(plist, p -> System.out.println(p.name));
   }
   public static void acceptAllEmployee(List<Person> plist, Consumer<P> con) {
      for(Person p : plist) {
         con.accept(p);
      }
   }
}// Person class
class Person {
   public String name;
   public Person(String name) {
      this.name = name;
   }
}

输出结果

raja
20
0
12
RAJA
ADITHYA
unknown
unknown