java中list动态多层分组
时间: 2023-09-27 17:11:14 浏览: 70
Java List集合返回值去掉中括号('[ ]')的操作
可以使用递归和Map实现动态多层分组,代码如下:
```java
public class ListGrouping {
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "Tom");
map1.put("age", 20);
map1.put("city", "Shanghai");
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "Jack");
map2.put("age", 18);
map2.put("city", "Beijing");
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "Lucy");
map3.put("age", 22);
map3.put("city", "Shanghai");
list.add(map3);
Map<String, Object> map4 = new HashMap<>();
map4.put("name", "Alex");
map4.put("age", 23);
map4.put("city", "Beijing");
list.add(map4);
Map<String, List<Map<String, Object>>> groupResult = group(list, Arrays.asList("city"));
System.out.println(groupResult);
}
public static Map<String, List<Map<String, Object>>> group(List<Map<String, Object>> list, List<String> keys) {
Map<String, List<Map<String, Object>>> result = new HashMap<>();
if (keys.size() == 0) {
result.put("data", list);
return result;
}
String key = keys.get(0);
for (Map<String, Object> map : list) {
String value = Objects.toString(map.get(key), "");
List<Map<String, Object>> groupList = result.computeIfAbsent(value, k -> new ArrayList<>());
groupList.add(map);
}
keys.remove(0);
for (Map.Entry<String, List<Map<String, Object>>> entry : result.entrySet()) {
entry.setValue(group(entry.getValue(), new ArrayList<>(keys)));
}
return result;
}
}
```
以上代码会根据map中的city属性进行分组,最终结果如下:
```
{
"Beijing": {
"data": [{
"age": 18,
"city": "Beijing",
"name": "Jack"
}, {
"age": 23,
"city": "Beijing",
"name": "Alex"
}]
},
"Shanghai": {
"data": [{
"age": 20,
"city": "Shanghai",
"name": "Tom"
}, {
"age": 22,
"city": "Shanghai",
"name": "Lucy"
}]
}
}
```
阅读全文