package com.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
public class Test7 {
public static void main(String[] args) {
List<Student> stuList = new ArrayList<Student>();
Student st1 = new Student("123","aaa");
Student st2 = new Student("234","bbb");
Student st3 = new Student("345","ccc");
Student st4 = new Student("345","ccc");
Student st5 = new Student("123","ddd");
stuList.add(st1);
stuList.add(st2);
stuList.add(st3);
stuList.add(st4);
stuList.add(st5);
//1.提取出list对象中的一个属性
Map<String, List<Student>> s = stuList.stream().collect(
Collectors.groupingBy(Student::getId));
s.forEach((k, v)->{
v.forEach(System.out::println);
});
//输出1:
/*Student [id=123 aaa]
Student [id=123 ddd]
Student [id=234 bbb]
Student [id=345 ccc]
Student [id=345 ccc]
*/
Object js = JSONObject.toJSON(s);
System.out.println(js);
//输出2:
/*{
"345":[{"name":"ccc","id":"345"},{"name":"ccc","id":"345"}],
"123":[{"name":"aaa","id":"123"},{"name":"ddd","id":"123"}],
"234":[{"name":"bbb","id":"234"}]
}
*/
}
}
java 8 分组
最新推荐文章于 2025-03-11 14:03:42 发布
本文介绍如何使用Java 8的Stream API对列表进行分组,并将分组后的结果转换为JSON格式输出。示例代码展示了创建学生对象列表、按ID分组以及将分组结果转换成JSON字符串的过程。
1万+

被折叠的 条评论
为什么被折叠?



