如何在 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 expression c.accept("Raja"); Consumer<Integer> con = (x) -> { // lambda expression 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
广告