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}]