How to implement the ObjIntConsumer interface using lambda expression in Java?


The ObjIntConsumer interface is a kind of functional interface and defined in java.util.function package. This functional interface expects an object-valued and int-valued argument as input and does not produce any output. It holds only one functional method, accept(Object, int).

Syntax

@FunctionalInterface
   public interface ObjIntConsumer {
      void accept(T t, int value)
}

In the below examples, we can implement the ObjIntConsumer interface by using a lambda expression.

Example-1

import java.util.function.*;

public class ObjIntConsumerInterfaceTest1 {
   public static void main(String args[]) {
      ObjIntConsumer<String> objIntConsumberObj = (t, value) -> {   // lambda expression
         if(t.length() > value) {
            System.out.println("String is bigger than the expected value");
         } else if(t.length() == value) {
            System.out.println("String is equal to expected value");
         } else {
            System.out.println("String is shorter than the expected value");
         }
      }; // end of lambda expression
      objIntConsumberObj.accept("tutorialspoint.com", 15);
      objIntConsumberObj.accept("tutorix.com", 15);
   }
}

Output

String is bigger than the expected value
String is shorter than the expected value


Example-2

import java.util.*;
import java.util.function.*;

public class ObjIntConsumerInterfaceTest2 {
   public static void main(String args[]) {
      ObjIntConsumer<List <Integer>> objIntConsumberObj = (t, value) -> {  // lamnda expression
         if(t.contains(value)) {
            System.out.println("Expected value is present in the string");
         } else {
            System.out.println("Expected value is not present in the string");
         }
      };  // end of lambda expression

      List<Integer> listObj = new ArrayList<Integer>();
      listObj.add(55);
      listObj.add(100);
      listObj.add(75);

      objIntConsumberObj.accept(listObj, 80);
      objIntConsumberObj.accept(listObj, 100);
   }
}

Output

Expected value is not present in the string
Expected value is present in the string

Updated on: 13-Jul-2020

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements