How to implement LongConsumer using lambda in Java?

Java 8Object Oriented ProgrammingProgramming

LongConsumer is a in-built functional interface from java.util.function package. This interface can accept a single long-valued argument as input and doesn't produce any output. It can also be used as the assignment target for a lambda expression or method reference and contains one abstract method: accept() and one default method: andThen().

Syntax

@FunctionalInterface
public interface LongConsumer

Example-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);
   }
}

Output

Display the next value to input : 1000
1001
Display the previous value to input : 1000
999


Example-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);
   }
}

Output

13 3 6 1 8
raja
Published on 10-Jan-2020 12:21:40
Advertisements