如何使用 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

更新于: 2020-07-13

130 次浏览

开启你的职业生涯 生涯

完成课程获取认证

开始
广告
© . All rights reserved.