如何在 Java 中使用 lambda 表示式實現ObjLongConsumer


ObjLongConsumer<T> 是從 java.util.function 包中來的函式介面。這個介面接受一個物件值長值作為輸入,但是不產生任何輸出。ObjLongConsumer<T> 可以用作lambda 表示式 方法 引用 的分配目標,並且只包含一個抽象方法:accept()

語法

@FunctionalInterface
public interface ObjLongConsumer<T> {
 void accept(T t, long value)
}

示例

import java.util.function.ObjLongConsumer;

public class ObjLongConsumerTest {
   public static void main(String[] args) {
      ObjLongConsumer<Employee> olc = (employee, number) -> {     // lambda expression
         if(employee != null) {
            System.out.println("Employee Name: " + employee.getEmpName());
            System.out.println("Old Mobile No: " + employee.getMobileNumber());
            employee.setMobileNumber(number);
            System.out.println("New Mobile No: " + employee.getMobileNumber());
         }
      };
      Employee empObject = new Employee("Adithya", 123456789L);
      olc.accept(empObject, 987654321L);
   }
}

// Employee class
class Employee {
   private String empName;
   private Long mobileNum;
   public Employee(String empName, Long mobileNum){
      this.empName = empName;
      this.mobileNum = mobileNum;
   }
   public String getEmpName() {
      return empName;
   }
   public void setEmpName(String empName) {
      this.empName = empName;
   }
   public Long getMobileNumber() {
      return mobileNum;
   }
   public void setMobileNumber(Long mobileNum) {
      this.mobileNum = mobileNum;
   }
}

輸出

Employee Name: Adithya
Old Mobile No: 123456789
New Mobile No: 987654321

更新於: 14-Jul-2020

231 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.