欢迎您的访问
专注架构,Java,数据结构算法,Python技术分享

Java8中Map新方法:compute使用详解

一、介绍

Java8更新后,Map接口中提供了compute方法。下面我们先看看官方文档的对它的使用说明.

Java8中Map新方法:compute使用详解

如果看完上面的还是不太明白的话,看下面的这个示例。然后再来看这段说明,你就明白的它的意思了。

二、使用

假如我们现在有一需求,需要统计一个字符串中各个单词出现的频率,然后从中找出频率最高的单词。让我们先来看看jdk8之前的写法。

public static void main(String[] args) {
    String str = "hello java, i am vary happy! nice to meet you";

    // jdk1.8之前的写法
    HashMap<Character, Integer> result1 = new HashMap<>(32);
    for (int i = 0; i < str.length(); i++) {
        char curChar = str.charAt(i);
        Integer curVal = result1.get(curChar);
        if (curVal == null) {
            curVal = 1;
        } else {
            curVal += 1;
        }
        result1.put(curChar, curVal);
    }
}

但是jdk8后,map给我们提供了更为便捷的接口方法,那就是本文要说的重点compute方法。

public static void main(String[] args) {
    String str = "hello java, i am vary happy! nice to meet you";

    // jdk1.8的写法
    HashMap<Character, Integer> result2 = new HashMap<>(32);
    for (int i = 0; i < str.length(); i++) {
        char curChar = str.charAt(i);
        result2.compute(curChar, (k, v) -> {
            if (v == null) {
                v = 1;
            } else {
                v += 1;
            }
            return v;
        });
    }
}

运行以上两段代码,发现运行的结构都是一样的。

{ =9, a=5, !=1, c=1, e=4, h=2, i=2, j=1, l=2, ,=1, m=2, n=1, o=3, p=2, r=1, t=2, u=1, v=2, y=3}

在这里可能有些同学不理解第二参数的含义,在这里简单说一下。

Function作为一个函数式接口,主要方法apply接收一个参数,返回一个值。这个有点类似数学中一元函数。

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}

而 BiFunction则是Function函数的升级版。聪明的同学可能会发现Function只能接受一个参数。假如我的函数体有两个参数,咋办呢。而BiFunction正是解决这一问题而出现的。

这两者的都不难。看示例。

@FunctionalInterface
public interface BiFunction<T, U, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    R apply(T t, U u);
 }

简单示例:

// 求一个数的平方
Function<Integer, Integer> fun1= arg -> arg * arg;
Integer apply = fun1.apply(10);
// 100
System.out.println(apply);

// 求输入两个的和
BiFunction<Integer, Integer, Integer> fun2 = (arg1, arg2) -> arg1 + arg2;
Integer sum = fun2.apply(10, 20);
// 30
System.out.println(sum);

三、其他

Map接口的compute方法的二元函数。如果key不存在或者key对应的value为null的话,则其value都是null。否则就是key对应的value值。(这点可以在官方文档中体现出来)

来源:blog.csdn.net/weixin_39723544/article/details/91359302

赞(0) 打赏
版权归原创作者所有,任何形式转载请联系作者;码农code之路 » Java8中Map新方法:compute使用详解

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏