如何在Java中使用Lambda表达式实现ObjIntConsumer接口?
ObjIntConsumer 接口是一种功能性 接口和在定义java.util.function包。该功能接口期望将一个对象-值 和整数-值 参数作为输入,并且不产生任何输出。它仅包含一种功能方法accept(Object,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
热门推荐
10 新年给妹妹祝福语简短
11 宝宝新生入学祝福语简短
12 生日贺卡祝福语 简短独特
13 英语简短祝福语给学生
14 初升高祝福语家长简短
15 乔迁仪式文案祝福语简短
16 长辈钻石婚祝福语简短
17 婚礼西装祝福语简短男士
18 离别简短的祝福语大全