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