Sunday, July 19, 2015

Java Lambda - LongConsumer Functional Interface

LongConsumer Functional Interface

LongConsumer Interface represents an operation that accepts long valued argument and returns no result. Previously we had discussed Consumer interface. I would recommend you to read that as LongConsumer is primitive long data type specialization of Consumer interface.

There are two different methods in LongConsumer interface. Let us understand both of them one by one.

accept() method
void accept(long value);

accept() method performs this operation on give argument. This method does not return any value. It accepts a parameter of type long.
Let us take simple example to understand this method.

      LongConsumer longConsumer = (a) -> System.out.println(a);
      longConsumer.accept(10); //Prints 10

andThen() method
      default LongConsumer andThen(LongConsumer after) {
            return (long t) -> { accept(t); after.accept(t); };

andThen() method returns a composed version of this and after LongConsumer that will perform respective operation in sequence. This method will throw NullPointerException if after is null.
Let us write two different LongConsumer. One for adding and another for multiplication.

LongConsumer adder = (a) -> System.out.println(a + a);

LongConsumer multiplier = (a) -> System.out.println(a * a);


Read about important java.util.function package’s interface here. Consumer, Function, Supplier, BinaryOperator & Predicate Functional Interfaces. I have also written on High Order functions using Function functional interface.

No comments:

Post a Comment

Ads Inside Post