数据格式化代码

发布时间 2023-07-07 12:29:24作者: Rover20230226

原数据形式

  

 优化后

  

 独立代码:

    // 数据格式化代码
    private Map<String, Set<String>> convertSpecList(List<String> specList) {
        Map<String, Set<String>> specMap = new HashMap<>();
        //TODO 参数校验
        if (CollectionUtils.isEmpty(specList)) {
            return null;
        }
        //TODO 修改结构代码
        for (String spec : specList) {
            // spec = "{'颜色': '黑色', '版本': '6GB+128GB'}"
            Map<String, String> map = JSON.parseObject(spec, Map.class);  // {'颜色': '黑色', '版本': '6GB+128GB'}
            Set<String> keys = map.keySet();
            for (String key : keys) {  // 颜色
                String value = map.get(key);  // 蓝色
                Set<String> specValue = specMap.get(key);
                if (specValue == null) {
                    specValue = new HashSet<>();
                }
                specValue.add(value);  // 蓝色
                // {'颜色': ['蓝色','黑色'], '版本': ['6GB+128GB','4GB+64GB']}
                specMap.put(key, specValue);
            }
        }

        return specMap;
    }