Kotlin - 如何根据字符的总长度拆分字符串列表

Ben*_*een 4 kotlin

我正在用 Kotlin 编写一个程序,将消息发布到休息端点。

val messages : List<String> = getMessageToSend();
webClient
    .post()
    .uri { builder -> builder.path("/message").build() }
    .bodyValue(PostMessageRequest(
        messages.joinToString("\n")
    ))
    .exchange()
    .block()
Run Code Online (Sandbox Code Playgroud)

但是,其余端点对发送的消息的最大大小有限制。我对 Kotlin 相当陌生,但我一直在寻找一种实用的方法来实现这一目标,但我正在努力。我知道如何用 Java 编写它,但我渴望正确地完成它。我想将messages列表拆分为列表列表,每个列表都限制为允许的最大大小,并且仅添加整个字符串,然后单独发布它们。我已经看过类似的方法chunked,但这似乎不够灵活,无法实现我想要做的事情。

例如,如果我的消息是[this, is, an, example]并且限制是 10,我希望我的列表列表是[[this, is an], [example]]

任何建议将不胜感激。

gid*_*dds 6

这看起来很像我以前遇到过的情况。\xc2\xa0 为了解决这个问题,我编写了以下通用扩展函数:

\n
/**\n * Splits a collection into sublists not exceeding the given size.  This is a\n * generalisation of [List.chunked]; but where that limits the _number_ of items in\n * each sublist, this limits their total size, according to a given sizing function.\n *\n * @param maxSize None of the returned lists will have a total size greater than this\n *                (unless a single item does).\n * @param size Function giving the size of an item.\n */\ninline fun <T> Iterable<T>.chunkedBy(maxSize: Int, size: T.() -> Int): List<List<T>> {\n    val result = mutableListOf<List<T>>()\n    var sublist = mutableListOf<T>()\n    var sublistSize = 0L\n    for (item in this) {\n        val itemSize = item.size()\n        if (sublistSize + itemSize > maxSize && sublist.isNotEmpty()) {\n            result += sublist\n            sublist = mutableListOf()\n            sublistSize = 0\n        }\n        sublist.add(item)\n        sublistSize += itemSize\n    }\n    if (sublist.isNotEmpty())\n        result += sublist\n\n    return result\n}\n
Run Code Online (Sandbox Code Playgroud)\n

实现有点麻烦,但使用起来非常简单。\xc2\xa0 在你的情况下,我希望你会做类似的事情:

\n
messages.chunkedBy(1024){ length + 1 }\n        .map{ it.joinToString("\\n") }\n
Run Code Online (Sandbox Code Playgroud)\n

给出一个字符串列表,每个字符串不超过 1024 个字符*。(+ 1当然是允许换行符的。)

\n

老实说,我很惊讶标准库中没有这样的东西。

\n

(* 除非任何初始字符串更长。)

\n