代码之家  ›  专栏  ›  技术社区  ›  menteith

使用流计算句子中每个字母的出现次数

  •  2
  • menteith  · 技术社区  · 6 年前

    我想计算一个句子中每个字母的出现次数并将结果存储在 Map<Character, Integer> . 使用一个简单的循环可以很容易地做到这一点,但是作为练习,我想使用流来编写它。我想用 collect(toMap()) 生成一个值为字符本身的映射(因此我使用 Function.identity() )以及出现的次数。我提出了以下(非编译)代码:

    "a simple sentence".chars()                
    .collect(toMap(Collectors.partitioningBy(Function.identity(), 
    Collectors.counting())));
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   amrender singh    6 年前

    请尝试以下操作:

    String string ="a simple sentence";
    Map<String, Long> map = 
     Arrays.stream(string.split("")).
     collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
        2
  •  3
  •   Ousmane D.    6 年前

    你已经接近了,要完成你已经开始的,你需要使用 mapToObj 中间操作和 groupingBy 收集器而不是 partitioningBy 具体如下:

    Map<Character, Long> result = "a simple sentence".chars()
                    .mapToObj(c -> (char) c)
                    .collect(groupingBy(Function.identity(),
                            counting()));
    

    或者,如果希望映射键是字符串,则可以执行以下操作:

    Map<String, Long> result = "a simple sentence".chars()
                    .mapToObj(c -> String.valueOf((char) c))
                    .collect(groupingBy(Function.identity(),
                            counting()));
    

    或者如果希望出现除空白字符以外的所有字符:

    Map<String, Long> result = "a simple sentence".chars()
                    .filter(c -> !Character.isSpaceChar(c))
                    .mapToObj(c -> String.valueOf((char) c))
                    .collect(groupingBy(Function.identity(),
                            counting()));
    

    或使用模式:

    Map<String, Long> result = 
         Pattern.compile("\\s+")
                .splitAsStream("a simple sentence")
                .flatMap(s -> Arrays.stream(s.split("")))
                .collect(groupingBy(Function.identity(),
                            counting()));
    

    使用模式更有效的版本:

    Map<String, Long> result = 
         Pattern.compile("") 
                .splitAsStream("a simple sentence")
                .filter(s -> !s.trim().isEmpty())
                .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));