如何在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 爸爸寿宴仪式祝福语简短