如何使用 lambda 在 Java 中实现 LongConsumer?
LongConsumer 是 java.util.function 包中一个内置的函数接口。此接口可以接收单个长整型值作为输入,并且不生成任何输出。它还可以用作lambda 表达式或方法 引用的赋值目标,并包含一个抽象方法:accept()和一个默认方法:andThen()。
语法
@FunctionalInterface public interface LongConsumer
示例 1
import java.util.function.LongConsumer;
public class LongConsumerLambdaTest {
public static void main(String[] args) {
LongConsumer displayNextVal = l-> { // lambda expression
System.out.println("Display the next value to input : "+l);
System.out.println(l+1);
};
LongConsumer displayPrevVal = l-> { // lambda expression
System.out.println("Display the previous value to input : "+l);
System.out.println(l-1);
};
LongConsumer displayPrevAndNextVal = displayNextVal.andThen(displayPrevVal);
displayPrevAndNextVal.accept(1000);
}
}输出
Display the next value to input : 1000 1001 Display the previous value to input : 1000 999
示例 2
import java.util.Arrays;
import java.util.function.LongConsumer;
public class LongConsumerTest {
public static void main(String[] args) {
long[] numbers = {13l, 3l, 6l, 1l, 8l};
LongConsumer longCon = l -> System.out.print(l + " ");
Arrays.stream(numbers).forEach(longCon);
}
}输出
13 3 6 1 8
广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP