Java8: Create HashMap with character count of a String

前端 未结 4 1088
情深已故
情深已故 2021-01-06 23:33

Wondering is there more simple way than computing the character count of a given string as below?

String word = \"AAABBB\";
    Map ch         


        
4条回答
  •  抹茶落季
    2021-01-07 00:14

    Hope this help : Java 8 Stream & Collector:

        String word = "AAABBB";
        Map charCount = word.chars().boxed().collect(Collectors.toMap(
                        k -> Character.valueOf((char) k.intValue()),
                        v -> 1,
                        Integer::sum));
        System.out.println(charCount);
    
    Output:
        {A=3, B=3}
    

提交回复
热议问题