Kotlin-如何在构建器块中迭代地图或列表

Kotlin-如何在构建器块中迭代地图或列表,kotlin,Kotlin,这可能是一个愚蠢的问题,但我想知道是否有可能在构建器块中迭代映射或列表 我正在构建HttpRequest,我想在列表或标题映射的顶部工作。举个例子,让我们想象一下这个场景: val headers1 = hashMapOf("Content-type" to "application/json") val headers2 = listOf("Content-type=application/json") 我真的更喜欢使用映射,而不是传递一个String=String列表,但如果它更简单或更简

这可能是一个愚蠢的问题,但我想知道是否有可能在构建器块中迭代映射或列表

我正在构建
HttpRequest
,我想在列表或标题映射的顶部工作。举个例子,让我们想象一下这个场景:

val headers1 = hashMapOf("Content-type" to "application/json")
val headers2 = listOf("Content-type=application/json")
我真的更喜欢使用映射,而不是传递一个
String=String
列表,但如果它更简单或更简洁,我可以接受

以下是我如何构建HttpRequest:

HttpRequest.newBuilder()
    .version(HttpClient.Version.HTTP_1_1)
    .timeout(Duration.ofSeconds(1))
    .uri(URI.create(endpoint))
    .method(method.value, HttpRequest.BodyPublishers.ofString(body))
    .header(<inject headers here>)
    .build()
HttpRequest.newBuilder()
.version(HttpClient.version.HTTP_1_1)
.超时(持续时间秒(1))
.uri(uri.create(端点))
.method(method.value,HttpRequest.bodypublisher.ofString(body))
.header()
.build()

是否可以在生成过程中添加/注入头?

您可以像这样迭代映射

val headers: Map<String, String> = /* ... */

HttpRequest.newBuilder()
    .version(HttpClient.Version.HTTP_1_1)
    .timeout(Duration.ofSeconds(1))
    .uri(URI.create(endpoint))
    .method(method.value, HttpRequest.BodyPublishers.ofString(body))
    .apply {
        headers.forEach { (key, value) -> setRequestHeader(key, value) }
    }
val头:Map=/**/
HttpRequest.newBuilder()
.version(HttpClient.version.HTTP_1_1)
.超时(持续时间秒(1))
.uri(uri.create(端点))
.method(method.value,HttpRequest.bodypublisher.ofString(body))
.申请{
headers.forEach{(键,值)->setRequestHeader(键,值)}
}