欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计文件中的字符个数(Kotlin)

程序员文章站 2022-07-05 20:01:13
...

代码:
统计文件中的字符个数(Kotlin)

import java.io.File

/**
 * Created by FangJu on 2020/1/28
 * 统计文件中字符个数
 */
fun main() {
    File("build.gradle").readText() //读取字符串
        .toCharArray()  // 转换为字符数组
        .filter {
            !it.isWhitespace()  //过滤空格
        }
        .groupBy {
            it  // 按照单个“char”分组
        }.map {
            it.key to it.value.size     //转换成Pair
        }.let {
            println(it.toString())
        }
}

结果:

[(p, 13), (l, 16), (u, 6), (g, 8), (i, 31), (n, 24), (s, 15), ({, 5), (d, 6), (', 16), (j, 9), (a, 12), (v, 8), (o, 25), (r, 16), (., 15), (e, 26), (t, 25), (b, 4), (k, 6), (m, 12), (1, 7), (3, 1), (6, 1), (}, 5), (x, 1), (0, 1), (-, 3), (S, 2), (N, 1), (A, 1), (P, 1), (H, 1), (O, 3), (T, 4), (c, 4), (C, 3), (y, 1), (=, 3), (8, 4), ((, 1), (), 1), (", 6), (:, 4), (,, 2), (4, 1), (2, 1), (K, 2)]
相关标签: Kotlin