怎么将数组多个对象的某个属性分组成下面那样的需求(java的处理方式)

原始数据处理后的样子是这样的,跟我需求还是不太一样,所以来请求帮助。

[{"partCode": "1111", "Price": "5000", "userName": "电脑"},{"partCode": "2222", "Price": "4000", "userName": "手机"},{"partCode": "3333", "Price": "2500", "userName": "手表"},{"partCode": "1111", "Price": "255", "userName": "耳机"},{"partCode": "1111", "Price": "550", "userName": "键盘"},{"partCode": "1111", "Price": "165", "userName": "鼠标"},{"partCode": "2222", "Price": "155", "userName": "耳机"},{"partCode": "3333", "Price": "50", "userName": "表带"},{"partCode": "2222", "Price": "35", "userName": "充电器"}]

然后需要处理成这样

[{"partCode": "1111","电脑":"5000“,"耳机":"255","键盘":"550","鼠标":"165"},{"partCode": "2222","手机":"4000","耳机":"155","充电器":"35"},{"partCode": "3333","手表":"2500","表带":"50"}]


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo2 {
    public static void main(String[] args) {
        String jsonStr = "[{\"partCode\": \"1111\", \"Price\": \"5000\", \"userName\": \"电脑\"},{\"partCode\": \"2222\", \"Price\": \"4000\", \"userName\": \"手机\"},{\"partCode\": \"3333\", \"Price\": \"2500\", \"userName\": \"手表\"},{\"partCode\": \"1111\", \"Price\": \"255\", \"userName\": \"耳机\"},{\"partCode\": \"1111\", \"Price\": \"550\", \"userName\": \"键盘\"},{\"partCode\": \"1111\", \"Price\": \"165\", \"userName\": \"鼠标\"},{\"partCode\": \"2222\", \"Price\": \"155\", \"userName\": \"耳机\"},{\"partCode\": \"3333\", \"Price\": \"50\", \"userName\": \"表带\"},{\"partCode\": \"2222\", \"Price\": \"35\", \"userName\": \"充电器\"}]";
        List<Map<String, Object>> beforeDataList = JSON.parseObject(jsonStr, List.class);

        // 按照 partCode 分组
        Map<String, List<Map<String, Object>>> groupByPartCodeList = beforeDataList.stream()
                .collect(Collectors.groupingBy(temp -> temp.get("partCode").toString()));

        // 遍历
        List<Map<String, Object>> afterDataList = groupByPartCodeList.entrySet().stream().map(temp -> {
            // Map<String, Object> afterDataMap = new HashMap<>();
            Map<String, Object> afterDataMap = Maps.newHashMap();
            afterDataMap.put("partCode", temp.getKey());
            temp.getValue().stream().forEach(temp2 -> afterDataMap.put(temp2.get("userName").toString(), temp2.get("Price").toString()));
            return afterDataMap;
        }).collect(Collectors.toList());

        System.out.println(afterDataList);
    }
}

[{手表=2500, partCode=3333, 表带=50}, {手机=4000, 充电器=35, 耳机=155, partCode=2222}, {电脑=5000, 鼠标=165, 耳机=255, 键盘=550, partCode=1111}]

 

你这个是jsonArray了,遍历下jsonArray ,

然后就是取值,拼接json