How to implement IntConsumer using lambda and method reference in Java?

Java 8Object Oriented ProgrammingProgramming

IntConsumer interface is a functional interface from java.util.function package in Java 8. This interface accepts a single int-valued argument as input but doesn't produce any output. Since it is a functional interface, it can be used as an assignment target for a lambda expression or method reference. It contains one abstract method: accept() and one default method: andThen().

Syntax

@FunctionalInterface
public interface IntConsumer {
   void accept(int value);
}

Example of Lambda Expression

import java.util.function.IntConsumer;

public class IntConsumerTest1 {
   public static void main(String[] args) {
      IntConsumer displayNextInt = i -> System.out.println("Next Int Value: " + (i+1));  // lambda
      IntConsumer displaySquare = i -> System.out.println("Int Square Value: " + (i*i)); // lambda
      IntConsumer displayBoth = displayNextInt.andThen(displaySquare);
      displayBoth.accept(25);
   }
}

Output

Next Int Value: 26
Int Square Value: 625


Example of Method reference

import java.util.function.IntConsumer;

public class IntConsumerTest2 {
   public static void main(String[] args) {
      IntConsumer consumer = IntConsumerTest2::print; // method reference
      consumer.accept(77);
   }
   static void print(int i) {
      System.out.println(i);
   }
}

Output

77
raja
Published on 17-Jan-2020 11:46:55
Advertisements