JAVA8 之 function 基础

function 包简介

在java8中新引入了一个包

这是一个重要的更新,牵扯到了lamada表达式和一系列的语法结构变动。

function包主要有六个比较重要的interface;

按照字典排序
/**
 * Represents an operation that accepts two input arguments and returns no
 * result.  This is the two-arity specialization of {@link Consumer}.
 * Unlike most other functional interfaces, {@code BiConsumer} is expected
 * to operate via side-effects.
 */
interface BiConsumer<T, U>

/**
 * Represents a function that accepts two arguments and produces a result.
 * This is the two-arity specialization of {@link Function}.
*/
interface BiFunction<T, U, R>

/**
 * Represents a predicate (boolean-valued function) of two arguments.  This is
 * the two-arity specialization of {@link Predicate}.
 */
interface BiPredicate<T, U>

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 */
interface Consumer<T> 

/**
 * Represents a function that accepts one argument and produces a result.
 */
interface Function<T, R> 

/**
 * Represents a predicate (boolean-valued function) of one argument.
 */
interface Predicate<T> 

其实还有几个家伙:如  

interface BinaryOperator<T> extends BiFunction<T,T,T>

因为该家伙就是继承的 function接口,把function接口的三个类型(两个入参,一个出参)变成了同一个,所以就不单独说了;

通过翻译软件得知。上面的接口大致的用途如下:

接口入参出参
BiConsumerT、Uvoid
BiFunctionT、UR
BiPredicateT、Uboolean
ConsumerT

void

FunctionTR
PredicateTboolean

小结:带BI的多一个入参。

 

例一:

借用上一篇文章的内容,我们在调用Collectors.toMap的时候 最后一个参数内容 为 

 (u, v) -> v
studentList.stream().collect(Collectors.toMap(Student::getAge, Student::getName, (u, v) -> v));

这里如果使用idea,我们ctrl+鼠标左键可以看到父类就是 

interface BinaryOperator<T> extends BiFunction<T,T,T> 

因为该方法满足两个入参+一个出参,同时我们看到toMap中的源码如下

    public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }

就是使用的 

BinaryOperator<U>

那么问题来了,我们怎么知道 

 (u, v) -> v

哪个是map的旧值,哪个是新值呢?我们到hashmap中的源码查看如下

发现前面的为旧值,后面的为新值。

例二:

我们再看一个例子

这里的 (k,v) 正好满足我们的BiConsumer ,两个入参,没有出参。我们点进去验证一下

foreach的源码入参正好就是biconsumer,和我们的猜想正好吻合。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值