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

3次阅读

共计 2955 个字符,预计需要花费 8 分钟才能阅读完成。

简介

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/

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

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

正文完
 0