将[{key1:value1,key2:value3},{key1:value2,key2:value4}]这种格式的数据格式转成{key1:[value1,value2],key2:[value3,value4]}这种数据格式。
数据库中保存的sku信息是 [{“颜色”:“白”,“尺码”:“M”},{“颜色”:“黑”,“尺码”:“L”}] 这种格式的json字符串,需要转换成 {“颜色”:[“白”,“黑”],“尺码”:[“M”,“L”]} 这种格式方便前端使用,这里有两种方式,第一种是自己写的(第一次碰到这个问题,不咋会写),第二种是请教别人,别人教的。
记录了自己平时遇到的问题的解决方式,方便以后遇到了再利用这些方式解决此类问题。
第一种:
public Map<String, Set<String>> getSkuMap(List<String> skuList) {
Map<String, Set<String>> maps = new HashMap<>();
skuList.forEach(item -> {
//把当前的商品规格属性由字符串转为map
Map skuMap = (Map) JSON.parse(item);
Set<String> strSet;
//遍历转换后的规格属性map
for (Object mapInfo : skuMap.entrySet()) {
//从最终返回的结果集中获取当前key的值
Set<String> valueSet = maps.get(((Map.Entry) mapInfo).getKey());
strSet = valueSet == null ? new HashSet<>() : valueSet;
//获取当前value值
String value = (String) ((Map.Entry) mapInfo).getValue();
//如果当前value值不为空 则添加到set中,然后再把set添加到map中
if (StrUtil.isNotBlank(value)) {
strSet.add(value);
maps.put((String) ((Map.Entry) mapInfo).getKey(), strSet);
}
}
});
return maps;
}
第二种:
public void mapStream() {
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
list.add(map1);
list.add(map2);
map1.put("颜色", "红色");
map1.put("尺码", "L码");
map2.put("颜色", "蓝色");
map2.put("尺码", "M码");
Map<String, ArrayList<String>> collect =
list.stream()
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.collectingAndThen(
Collectors.mapping(Map.Entry::getValue, Collectors.toList()),
ArrayList::new)));
System.out.println(collect);
}