关于java:巧用HashMap一行代码统计单词出现次数

简介

JDK是在始终在迭代更新的,很多咱们相熟的类也悄悄的增加了一些新的办法个性。比方咱们最罕用的HashMap。

明天给大家讲一下HashMap在JDK8中增加的两个新办法compute和merge,从而实现一行代码实现单词统计的性能。一起来看看吧。

爱在JDK8之前

JDK8为咱们引入了很多十分十分有用新个性,比方Stream和lambda表达式,能够让咱们的程序更加简洁。

如果咱们须要统计一个数组中单词呈现的次数该怎么做呢?

这里不是讲算法,所以能够间接应用HashMap:

public void countBefore8(){
        Map<String,Integer> wordCount=  new HashMap<>();
        String[] wordArray= new String[]{"we","are","the","world","we"};
        for(String word: wordArray){
            //如果存在则加1,否则将值设置为1
            if(wordCount.containsKey(word)) {
                wordCount.put(word, wordCount.get(word) + 1);
            }else{
                wordCount.put(word, 1);
            }
        }
    }

基本上流程是下面样子的。咱们对数组进行遍历,而后判断这个单词是否存在于hashMap中,如果存在则+1。

逻辑很简略,然而看起来有些臃肿。

别怕,咱们有JDK8。

JDK8中应用compute

先看下JDK8中compute的定义:

default V compute(K key,
            BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = get(key);

        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            // delete mapping
            if (oldValue != null || containsKey(key)) {
                // something to remove
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                return null;
            }
        } else {
            // add or replace old mapping
            put(key, newValue);
            return newValue;
        }
    }

能够看到compute有第二个参数BiFunction,BiFunction就是一个函数,输出两个参数,返回一个参数。

BiFunction的两个参数别离是key和key所对应的oldValue。

可思考到咱们的单词统计,咱们能够间接将oldValue+1 即可。所以应用compute,能够将办法改写为:

public void countAfter8WithCompute(){
        Map<String,Integer> wordCount=  new HashMap<>();
        String[] wordArray= new String[]{"we","are","the","world","we"};
        Arrays.asList(wordArray).forEach(word ->{
            wordCount.putIfAbsent(word,0);
            wordCount.compute(word,(w,count)->count+1);
        });
    }

当然,咱们能够将putIfAbsent放到compute中:

public void countAfter8WithCompute2(){
        Map<String,Integer> wordCount=  new HashMap<>();
        String[] wordArray= new String[]{"we","are","the","world","we"};
        Arrays.asList(wordArray).forEach(word -> wordCount.compute(word,(w, count)->count == null ? 1 : count + 1));
    }

一行代码就实现了。

JDK8中应用merge

再看看merge办法:

default V merge(K key, V value,
            BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        Objects.requireNonNull(value);
        V oldValue = get(key);
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue, value);
        if (newValue == null) {
            remove(key);
        } else {
            put(key, newValue);
        }
        return newValue;
    }

merge办法须要3个参数,第一个参数是key,第二个参数是key对应的oldValue为空的值,也就是为空的默认值,第三个参数是一个BiFunction参数。

不同的是BiFunction的第一个参数是oldValue,第二个参数是value。

生成newValue的逻辑是:如果oldValue不存在,则应用value。如果oldValue存在,则调用BiFunction对oldValue和Value进行合并。

咱们能够写出相应的代码如下:

 public void countAfter8WithMerge(){
        Map<String,Integer> wordCount=  new HashMap<>();
        String[] wordArray= new String[]{"we","are","the","world","we"};
        Arrays.asList(wordArray).forEach(word->wordCount.merge(word, 1, (oldCount, one) -> oldCount + one));
    }

前面的函数能够用Integer::sum代替:

 public void countAfter8WithMerge(){
        Map<String,Integer> wordCount=  new HashMap<>();
        String[] wordArray= new String[]{"we","are","the","world","we"};
        Arrays.asList(wordArray).forEach(word->wordCount.merge(word, 1, Integer::sum));
    }

本文的例子https://github.com/ddean2009/learn-java-base-9-to-20/tree/master/java-base

本文已收录于 http://www.flydean.com/wordcount-in-one-line/

最艰深的解读,最粗浅的干货,最简洁的教程,泛滥你不晓得的小技巧等你来发现!

欢送关注我的公众号:「程序那些事」,懂技术,更懂你!

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据