用java 8计算字数

我试图在java 8中实现一个字数统计程序,但我无法使它工作。 该方法必须将字符串作为参数并返回Map

当我以旧java方式进行时,everthing工作正常。 但是当我尝试在java 8中执行它时,它返回一个映射,其中键是空的,具有正确的出现次数。

这是我的java 8风格的代码:

 public Map countJava8(String input){ return Pattern.compile("(\\w+)").splitAsStream(input).collect(Collectors.groupingBy(e -> e.toLowerCase(), Collectors.reducing(0, e -> 1, Integer::sum))); } 

这是我在正常情况下使用的代码:

 public Map count(String input){ Map wordcount = new HashMap(); Pattern compile = Pattern.compile("(\\w+)"); Matcher matcher = compile.matcher(input); while(matcher.find()){ String word = matcher.group().toLowerCase(); if(wordcount.containsKey(word)){ Integer count = wordcount.get(word); wordcount.put(word, ++count); } else { wordcount.put(word.toLowerCase(), 1); } } return wordcount; } 

主要方案:

 public static void main(String[] args) { WordCount wordCount = new WordCount(); Map phrase = wordCount.countJava8("one fish two fish red fish blue fish"); Map count = wordCount.count("one fish two fish red fish blue fish"); System.out.println(phrase); System.out.println(); System.out.println(count); } 

当我运行这个程序时,我的输出:

 { =7, =1} {red=1, blue=1, one=1, fish=4, two=1} 

我认为splitAsStream方法splitAsStream正则表达式中的匹配元素作为Stream 。 我该如何纠正?

问题似乎是你实际上是通过单词分裂 ,即你流过的不是一个单词的所有内容,或者是单词之间的内容 。 不幸的是,似乎没有相同的方法来流式传输实际的匹配结果(很难相信,但我没有发现任何;如果你知道一个,请随意评论)。

相反,您可以使用\W而不是\W来分割非单词。 另外,如注释中所述,通过使用String::toLowerCase而不是lambda和Collectors.summingInt ,可以使其更具可读性。

 public static Map countJava8(String input) { return Pattern.compile("\\W+") .splitAsStream(input) .collect(Collectors.groupingBy(String::toLowerCase, Collectors.summingInt(s -> 1))); } 

但恕我直言,这仍然很难理解,不仅仅是因为“反向”查找,而且很难推广到其他更复杂的模式。 就个人而言,我会选择“旧学校”解决方案,也许使用新的getOrDefault变得更紧凑。

 public static Map countOldschool(String input) { Map wordcount = new HashMap<>(); Matcher matcher = Pattern.compile("\\w+").matcher(input); while (matcher.find()) { String word = matcher.group().toLowerCase(); wordcount.put(word, wordcount.getOrDefault(word, 0) + 1); } return wordcount; } 

两种情况下的结果似乎相同。

尝试这个。

  String in = "go go go go og sd"; Map map = new HashMap(); //Replace all punctuation with space String[] s = in.replaceAll("\\p{Punct}", " ").split("\\s+"); for(int i = 0; i < s.length; i++) { map.put(s[i], i); } Set st = new HashSet(map.keySet()); for(int k = 0; k < s.length; k++) { int i = 0; Pattern p = Pattern.compile(s[k]); Matcher m = p.matcher(in); while (m.find()) { i++; } map.put(s[k], i); } for(String strin : st) { System.out.println("String: " + strin.toString() + " - Occurrency: " + map.get(strin.toString())); } System.out.println("Word: " + s.length); 

这是输出

字符串:sd,Occurrency:1

字符串:go,Occurrency:4

字符串:og,Occurrency:1

字:6