Sunday, August 19, 2018

java8 Numeric Object Consumer examples | Functional Interface tutorials

In my previous posts, We learned with examples of various consumer interfaces as follows


Primitive Consumer functional interfaces are defined in java.util.function package.
It has an only single abstract method which takes object value and other numeric value and results in nothing.
This accepts two values as input like BiConsumer interface. All functional interfaces can be used as a variable assigned with lambda expression or method reference

ObjIntConsumer<T>

java.util.function.ObjIntConsumer is a functional interface. It has a single abstract method
accept(T t, integer value) takes two arguments
t is an object and value is an integer

Method Reference example

Method reference is declared and called with double colon operator, This assigned with Consumer, calling accept() method with two arguments and returns nothing.

import java.util.function.ObjIntConsumer;
public class MethodReferenceExample {
  static void append(String str, int value) {
    System.out.println(str+value);
   }
   public static void main(String[] args) {
    ObjIntConsumer<String> IntToDoubleFunction = MethodReferenceExample::append;
    IntToDoubleFunction.accept("Hello",4);
    }
}
The output of the above-generated code is
Hello4

Lambda Expression Example

Here lambda expression declared by passing two parameters and assigned with ObjIntConsumer interface. Calling accepts with Object and int value and returns nothing.

ObjDoubleConsumer <String> objDoubleConsumer = ( v1 , v2 ) -> { System.out.println(v1 + " " +v2);};
objDoubleConsumer.accept("object",1d);
Output is

test 1

ObjLongConsumer<T>

java.util.function.ObjLongConsumer is a functional interface. It has single abstract method - accept(Object,primitive value), Takes object and integer value as input and returns no result


ObjLongConsumer <String> objLongConsumer = ( v1 , v2 ) -> { System.out.println(v1 + " " +v2);};
objLongConsumer.accept("object",4l);
The output of the above code execution is

object 4

Related article


EmoticonEmoticon