在工作中我需要,我需要递归处理复杂嵌套的JSON字符串,然后处理方法有多种,为了代码通用性,我想要把处理方法当作参数,传入到函数中,然后根据不同的处理方法处理字符串。通过查资料得知,可以使用函数式接口来实现此功能。
函数式接口(Functional Interface)就是一个有且仅有一个抽象方法的接口。
定义
Java8新增加的函数接口放在java.util.function
包中,一般Java8提供的接口够用了。当然也可以自定义,比如可按照以下方式:
@FunctionalInterface
public interface UpperCaseString<T,U> {
public String upperString(String t,String u);
}
Java8函数接口介绍
从接口命名来看,其实函数接口类型分为以下几类
Function接口
Fcuntion接口接受一个参数,返回一个的结果。
@Test
public void testLongFunction() {
//LongFunction接口一个long类型的数据,返回一个Object类型的数据
LongFunction<String> function = t -> String.valueOf(t);
String result = function.apply(12l);
System.out.println(result);
}
其他还有
- DoubleToIntFunction 接受一个double类型输入,返回一个int类型结果。
- ToDoubleBiFunction<T,U> 接受两个输入参数,返回一个double类型结果。
Supplier接口
Supplier接口不接受参数,但是提供一个返回值。
@Test
public void testSupplier() {
//不接受参数,返回一个long数据
LongSupplier supplier = () -> 2l;
System.out.println(supplier.getAsLong());
}
其他还有
- IntSupplier 不接受参数,返回一个int数据。
- DoubleSupplier 不接受参数,返回一个double数据。
Predicate接口
Predicate接口接收一个参数,返回一个Boolean类型值。
@Test
public void testPredicate() {
//接受两个String参数,取小写之后返回是否相等
BiPredicate<String, String> predicate = (t,u) -> t.toLowerCase().equals(u.toLowerCase());
System.out.println(predicate.test("AAb", "aaB"));
}
其他还有
- DoublePredicate 接受一个Double类型的数据,返回Boolean类型
Consumer接口
Consumer接口就是接受一个参数,不返回结果,即消费数据
@Test
public void testConsumer() {
//接受一个int类型,先加1,然后再打印
IntConsumer consumer = t -> System.out.println(t+1);
consumer.accept(2);
}
其他还有
- BiConsumer 接受两个参数,不返回结果
Operator接口
Operator接口是继承与Function接口,所以使用类似。UnaryOperator<T>
一元操作符接口,BinaryOperator<T>
二元操作符接口,一般多用于操作计算。
@Test
public void testOperator() {
BinaryOperator<Integer> binaryOperator = (t,u) -> t+u;
System.out.println(binaryOperator.apply(2, 3));
System.out.println(BinaryOperator.maxBy(Double::compareTo).apply(2.5, 4.5));
BinaryOperator<String> stringOperator = BinaryOperator.minBy(Comparator.naturalOrder());
System.out.println(stringOperator.apply("A","B"));
BinaryOperator<String> stringOperator2 = BinaryOperator.minBy(String::compareTo);
System.out.println(stringOperator2.apply("2020-01-14","2020-01-13"));
}
其他还有
- IntUnaryOperator 接受一个参数同为类型int,返回值类型也为int。
- LongBinaryOperator 接受两个参数同为类型long,返回值类型也为long。
总结
上述是介绍了几种函数式接口,其他也还有很多,但是其他就是另外的变式,原理都是共通的。函数式接口可以隐式转换为 lambda 表达式。这样我们平时编程时候比较代码简洁,用起来也是非常方便,值得使用。