如何在 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
广告