Java 8 Examples

Java 8 LongConsumer example

Posted On
Posted By admin

In this blog post, I will be explaining how the Java 8 functional interface LongConsumer works. To know more about functional interfaces, you can refer this blog post.

The LongConsumer interface provides a method called accept. It accepts a single parameter of long data type. It does not return anything, it returns a void. So it operates via side effects i.e. it modifies the parameter passed in.The LongConsumer interface is a specialization of the Consumer interface. While the Consumer interface accepts any data type, the LongConsumer interface accepts a long value. To see an example of the Consumer interface, refer to this blog post.

LongConsumer Example

Consider the following code snippet:

public class LongConsumerDemo {

  public static void main(String args[]) {
    LongConsumer decrementBy5 = (num) -> System.out.println("Input:"+num+", Incremented Value:"+(num-5));
    decrementBy5.accept(12);
    decrementBy5.accept(23);
  }

}

 

Here, the LongConsumer.accept method accepts a long value. It decrements the value by 5 and prints the result.  So when the above code is executed, it will print the following output:

Input:12, Incremented Value:7
Input:23, Incremented Value:18

You can get the source code for this example along with other code for other Java 8 examples at the Github repository here.



If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment