我有給定格式的 JSON 資料:
dataset = [
{ 'name': 'Sayantan', 'section': 'A', 'detail': 'complete' },
{ 'name': 'Charu', 'section': 'B', 'detail': 'complete' },
{ 'name': 'Sanhati', 'section': 'C', 'detail': 'inprogress' },
]
我想將其轉換為 <String, List<>> 的映射并以下列格式獲取:
{'complete': [{'detail': 'complete', 'name': 'Sayantan', 'section': 'A'},
{'detail': 'complete', 'name': 'Charu', 'section': 'B'}],
'inprogress': [{'detail': 'inprogress', 'name': 'Sanhati', 'section': 'C'}]}
我在 Kotlin 方面沒有太多經驗,我主要在 Python 中處理此類案例,并且我設法撰寫了以下內容:
val mapOfInterest = mutableMapOf<String, List<DataResource>>()
for (data in datasets) {
val mapKey = data.detail
if (!mapOfInterest.containsKey(mapKey)) {
if (mapKey != null) {
mapOfInterest[mapKey] = listOf(data)
} else {
mapOfInterest[mapKey] // I am stuck here
}
}
}
我無法通過使用向地圖鍵值添加資料add(),任何想法或線索都會有所幫助。
uj5u.com熱心網友回復:
有一個 stdlib 函式可以滿足您的需求,稱為groupBy:
val mapOfInterest = dataset.groupBy { it.detail }
uj5u.com熱心網友回復:
在 Kotlin 中,集合默認情況下是不可變的:https ://kotlinlang.org/docs/collections-overview.html 。所以 List 沒有add()方法。
您可以mutableListOf()改用,但正如 Joffrey 已經指出的那樣,在 Kotlin 中執行此操作的“正確”方法是使用標準函式groupBy() https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group -by.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441368.html
