一,List分组
// 1.java8之前
// 按照Name分组,准备Map,此处使用LinkedHashMap的原因是为了保证后续遍历的时候,按照分组时的add顺序来操作
Map> groupMap = new LinkedHashMap>();
for(Vo groupVo : dataList) {
String groupName = groupVo.getGroupName();
//如果Map中的key包含此时的groupName,则取出Value,直接add此实体
if(groupLimitNeedVO.containsKey(groupName)) {
groupLimitNeedVO.get(groupName).add(groupVo);
//否则的话,新建一个key为groupName的List,并将groupName作为key,list作为value放入map
}else {
List groupList = new LinkedList();
groupList.add(groupVo);
groupLimitNeedVO.put(groupName, groupList);
}
}
// 遍历
Set keySet = groupMap.keySet();
for(String groupName : keySet) {
System.out.printf("groupName"+)groupName;
}
// 2.java8的流分组
// 单条件
Map> groupMap = dataList.stream()
.collect(Collectors.groupingBy(Vo::getGroupName));
//.collect(Collectors.groupingBy( (Vo v) -> v.getGroupName() ))
// 多级
Map>> groupMap = dataList.stream().collect(
Collectors.groupingBy(Vo::getGroupName1),Collectors.groupingBy(Vo::getGroupName2));
二,JSON分组
// 1.单条件
var map = {};
var dest = [];
for(var i = 0; i < datas.length; i++){
var ai = datas[i];
if(!map[ai.currency]){// 自定义分组
dest.push({
title: ai.currency,// 自定义分组
name: i,
content: [ai]
});
map[ai.currency] = ai; // 自定义分组
}else{
for(var j = 0; j < dest.length; j++){
var data = dest[j];
if(data.title == ai.currency){// 自定义分组
data.content.push(ai);
break;
}
}
}
}
// 2.多条件 方法内传分组对象的数组,即可实现多次分组
function createTree(arr,keys) {
function createObj(arr, arrORobj, keys, start) {
for (let i = 0; i < arr.length; i++) {
// 当不存在一个排序的key,返回[]
if (start >= keys.length) {
let newArray=Array.isArray(arrORobj)?arrORobj:[]
return newArray.concat(arr[i])
}
let curKey = keys[start]
let curVal = arr[i][curKey]
if(!curVal)continue
// 存在key对应的值存在,传入{}构造
let newObj = arrORobj[curVal] ? arrORobj[curVal] : {}
arrORobj[curVal] = createObj([arr[i]], newObj, keys, start + 1)
}
// 存在一个排序的key,返回{}
return arrORobj
}
return createObj(arr,{},keys,0)
};
var obj1=[
{
"demp":"001",
"line":"a",
"id":"1",
},
{
"demp":"001",
"line":"b",
"id":"2",
},
{
"demp":"001",
"line":"c",
"id":"3",
},
{
"demp":"002",
"line":"a",
"id":"4",
},
{
"demp":"002",
"line":"b",
"id":"5",
},
{
"demp":"002",
"line":"b",
"id":"6",
}
];
createTree(obj1,['demp','line']);
参考:
https://cloud.tencent.com/developer/article/1446684
https://www.cnblogs.com/zhengyb/p/10106564.html