Java 8 - LongConsumer interface example

Posted on December 13, 2016


java.util.function.LongConsumer is a functional interface whose functional method is  accept(long value). The LongConsumer interface represents an operation that takes a single argument of long type and returns no result.

Example #1

The following example shows how to use the accept () method of the LongConsumer interface with lambda expression.

LongConsumerExample1.java

package com.boraji.tutorail.lambda;

import java.util.function.LongConsumer;

/**
 * @author imssbora
 */
public class LongConsumerExample1 {
   public static void main(String[] args) {
      LongConsumer consumer = (a) -> {
         long b = a * a;
         System.out.println(b);
      };
      consumer.accept(10);
      consumer.accept(100);
      consumer.accept(1000);
   }
}

Output

100
10000
1000000

Example #2

The following example shows how to use the default andThen() of the LongConsumer interface with lambda expression.

LongConsumerExample2.java

package com.boraji.tutorail.lambda;

import java.util.function.LongConsumer;

/**
 * @author imssbora
 */
public class LongConsumerExample2 {
   public static void main(String[] args) {
      LongConsumer consumer1 = a -> {
         long square = a * a;
         System.out.println("Square=" + square);
      };

      LongConsumer consumer2 = a -> {
         long cube = a * a * a;
         System.out.println("Cube=" + cube);
      };

      // Using andThen() method
      consumer1.andThen(consumer2).accept(10);
      System.out.println();
      consumer2.andThen(consumer1).accept(15);

   }
}

Output

Square=100
Cube=1000

Cube=3375
Square=225