高校网站群建设,音乐网站建立,正规网站制作公司哪家好,江苏工程建设信息网在Java中#xff0c;有一些常见的函数式接口可以用于支持函数式编程和Lambda表达式的使用。以下是一些常见的函数式接口#xff1a;
Predicate#xff1a;用于判断输入的值是否满足某个条件。它包含方法test#xff0c;接收一个参数并返回一个布尔值。Function#xff1a…在Java中有一些常见的函数式接口可以用于支持函数式编程和Lambda表达式的使用。以下是一些常见的函数式接口
Predicate用于判断输入的值是否满足某个条件。它包含方法test接收一个参数并返回一个布尔值。Function用于将一个输入值映射为一个输出值。它包含方法apply接收一个参数并返回一个结果。Consumer用于执行某个操作并消耗输入值没有返回值。它包含方法accept接收一个参数但不返回任何结果。Supplier用于提供一个值或对象。它不接收任何参数但会返回一个值或对象。UnaryOperator用于对单个输入进行操作并产生相同类型的输出。它继承自Function接口接收一个参数并返回一个相同类型的结果。BinaryOperator用于对两个输入进行操作并产生相同类型的输出。它继承自BiFunction接口接收两个参数并返回一个相同类型的结果。BiFunction用于将两个输入值映射为一个输出值。它包含方法apply接收两个参数并返回一个结果。Runnable用于定义执行的代码块没有输入参数和返回值。它包含方法run用于执行代码块。Comparator用于比较两个对象的顺序。它包含方法compare接收两个参数并返回一个表示顺序的整数值。
各个函数接口的简单示例如下
1 Predicate
用于判断输入的值是否满足某个条件。
FunctionalInterface
interface PredicateT {boolean test(T t);
}// 示例判断一个整数是否为正数
PredicateInteger isPositive (num) - num 0;
System.out.println(isPositive.test(5)); // 输出true
System.out.println(isPositive.test(-2)); // 输出false
2 Function
用于将一个输入值映射为一个输出值。
FunctionalInterface
interface FunctionT, R {R apply(T t);
}// 示例将字符串转换为整数
FunctionString, Integer stringToInt Integer::parseInt;
System.out.println(stringToInt.apply(123)); // 输出123
3 Consumer
用于执行某个操作并消耗输入值没有返回值。
FunctionalInterface
interface ConsumerT {void accept(T t);
}// 示例打印字符串长度
ConsumerString printLength str - System.out.println(str.length());
printLength.accept(Hello); // 输出5
4 Supplier
用于提供一个值或对象。
FunctionalInterface
interface SupplierT {T get();
}// 示例生成随机数
SupplierInteger randomGenerator () - (int) (Math.random() * 100);
System.out.println(randomGenerator.get()); // 输出随机生成的一个整数
5 UnaryOperator
对单个输入进行操作并产生相同类型的输出。
FunctionalInterface
interface UnaryOperatorT extends FunctionT, T {// 继承自Function接口省略了apply方法的声明
}// 示例对整数进行平方操作
UnaryOperatorInteger square num - num * num;
System.out.println(square.apply(5)); // 输出25
6 BinaryOperator
对两个输入进行操作并产生相同类型的输出。
FunctionalInterface
interface BinaryOperatorT extends BiFunctionT,T,T {// 继承自BiFunction接口省略了apply方法的声明
}// 示例对两个整数求最大值
BinaryOperatorInteger max (a, b) - a b ? a : b;
System.out.println(max.apply(5, 3)); // 输出5
7 BiConsumer
对两个输入值执行某个操作没有返回值。
FunctionalInterface
interface BiConsumerT, U {void accept(T t, U u);
}// 示例打印两个整数的和
BiConsumerInteger, Integer printSum (a, b) - System.out.println(a b);
printSum.accept(2, 3); // 输出5
8 BiFunction
将两个输入值映射为一个输出值。
FunctionalInterface
interface BiFunctionT, U, R {R apply(T t, U u);
}// 示例将两个字符串拼接起来
BiFunctionString, String, String concatenate (str1, str2) - str1 str2;
System.out.println(concatenate.apply(Hello, , World!)); // 输出Hello, World!
9 IntPredicate
用于判断输入的整数是否满足某个条件。
FunctionalInterface
interface IntPredicate {boolean test(int value);
}// 示例判断一个整数是否为偶数
IntPredicate isEven num - num % 2 0;
System.out.println(isEven.test(4)); // 输出true
System.out.println(isEven.test(7)); // 输出false