Java 内置四大核心函数式接口
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
Consumer 消费型接口 | T | void | 对类型为T的对象应用操作,包含方法:void accept(T t) |
Supplier 供给型接口 | 无 | T | 返回类型为T的对象,包含方法:T get() |
Function<T, R> 函数型接口 | T | R | 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t) |
Predicate 断定型接口 | T | boolean | 确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法:boolean test(T t) |
其他接口
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
BiFunction<T, U, R> | T U | R | 对类型为T, U 参数应用操作,返回 R 类型的结 果。包含方法为: R apply(T t, U u); |
UnaryOperator< T > (Function子接口) | T | T | 对类型为T的对象进行一元运算,并返回T类型的 结果。包含方法为:T apply(T t); |
BinaryOperator< T > (BiFunction 子接口) | T T | T | 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为: T apply(T t1, T t2); |
BiConsumer<T, U> | T U | void | 对类型为T, U 参数应用操作。包含方法为:void accept(T t, U u) |
BiPredicate<T,U> | T U | boolean | 包含方法为: boolean test(T t,U u) |
ToIntFunction < T > ToLongFunction< T > ToDoubleFunction< T > | T | int long double | 分别计算int、long、double值的函数 |
IntFunction< R > LongFunction< R > DoubleFunction< R > | int long double | R | 参数分别为int、long、double 类型的函数 |
使用举例
举例一:
@Test
public void test1() {
happyTime( 500, new Consumer<Double>() {
@Override
public void accept(Double aDouble) {
System.out.println( "学习太累了,去天上人间买了瓶矿泉水,价格为:" + aDouble );
}
} );
System.out.println( "********************" );
happyTime( 400, money -> System.out.println( "学习太累了,去天上人间喝了口水,价格为:" + money ) );
}
public void happyTime(double money, Consumer<Double> con) {
con.accept( money );
}
举例二:
@Test
public void test2() {
List<String> list = Arrays.asList( "北京", "南京", "天津", "东京", "西京", "普京" );
List<String> filterStrs = filterString( list, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains( "京" );//包含
}
} );
System.out.println( filterStrs );
List<String> filterStrs1 = filterString( list, s -> s.contains( "京" ) );
System.out.println( filterStrs1 );
}
//根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定
public List<String> filterString(List<String> list, Predicate<String> pre) {
ArrayList<String> filterList = new ArrayList<>();
for (String s : list) {
if (pre.test( s )) {
filterList.add( s );
}
}
return filterList;
}