记一段 Kotlin 处理 HashMap 数据结构的代码

Kotlin 代码:

    fun saveDataJson(scenarioId: Long) {
        val data = nodeModelFieldsDao.findByScenarioId(scenarioId)
        println("data=${JSON.toJSONString(data)}")
        println("开始执行 saveDataJson")
        val modelCodeSet = mutableSetOf<String>()
        data.forEach {
            it.modelCode?.let { v -> modelCodeSet.add(v) }
        }
        println("modelCodeSet=${JSON.toJSONString(modelCodeSet)}")
        val dataJsonObj = hashMapOf<String, HashMap<String?, String?>>()
        modelCodeSet.forEach {
            val mc = it
            dataJsonObj[mc] = hashMapOf() // 这一句话很重要,先初始化 dataJsonObj[mc]
            data.forEach {
                val modelCode = it.modelCode
                if (mc == modelCode) {
                    dataJsonObj[mc]?.set(it.fieldCode, it.value)
                }
            }
        }

        val dataJsonStr = JSON.toJSONString(dataJsonObj)
        println("dataJsonStr=${dataJsonStr}")

        val record = dataJsonDao.findByScenarioId(scenarioId)
        if (record == null) {
            val dataJson = DataJson()
            dataJson.dataJson = dataJsonStr
            dataJson.scenarioId = scenarioId
            dataJsonDao.save(dataJson)
        } else {
            record.dataJson = dataJsonStr
            record.scenarioId = scenarioId
            record.gmtModified = Date()
            dataJsonDao.save(record)
        }

        println("执行完成 saveDataJson")
    }

js 代码是:

var models = new Set();
for (var i = 0; i < data.length; i++) {
    var m = data[i];
    console.log(`m=${JSON.stringify(m)}`);
    let model_code = m.model_code;
    console.log(`model_code=${model_code}`);
    models.add(model_code);
}
console.dir(models);

var model_fields_map = {};
models.forEach(((model_code, index, array) => {
    model_fields_map[model_code] = {};
    data.map(m => {
        if (m.model_code == model_code) {
            model_fields_map[model_code][m.field_code] = `${m.field_output_code}|${m.data_type}|${m.setter_config_json}`
        }
    });
}));
上一篇:hbase源码系列(五)Trie单词查找树


下一篇:阿里高级技术专家:成长路上如何破局?