如何使用Java中的lambda表示式來實現ObjIntConsumer介面?


ObjIntConsumer介面是一種函式介面,定義在java.util.package包中。此函式介面期望一個物件值和一個int值作為輸入,並且不產生任何輸出。它僅包含一個函式方法,accept物件int)。

語法

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

在以下示例中,我們可以使用lambda表示式來實現ObjIntConsumer介面。

示例 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);
   }
}

輸出

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


示例 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);
   }
}

輸出

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

更新於: 13-07-2020

260 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.