如何在Java中使用lambda实现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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短