作业票list使用stream更据作业票id进行分类
时间: 2024-05-19 07:14:25 浏览: 54
作业管理系统,维普作业管理系统,Python
假设我们有一个作业票类,其属性包括id、姓名、状态等。
首先我们需要创建一个作业票的列表:
List<HomeworkTicket> homeworkTicketList = new ArrayList<>();
然后我们可以使用stream对其进行分类:
Map<String, List<HomeworkTicket>> groupedHomeworkTicketList = homeworkTicketList.stream()
.collect(Collectors.groupingBy(HomeworkTicket::getId));
这段代码会将homeworkTicketList按照id进行分类,并返回一个Map,其中key为id,value为对应id的作业票列表。
完整代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class HomeworkTicket {
private String id;
private String name;
private String status;
public HomeworkTicket(String id, String name, String status) {
this.id = id;
this.name = name;
this.status = status;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getStatus() {
return status;
}
public static void main(String[] args) {
List<HomeworkTicket> homeworkTicketList = new ArrayList<>();
homeworkTicketList.add(new HomeworkTicket("1", "张三", "已完成"));
homeworkTicketList.add(new HomeworkTicket("1", "李四", "已完成"));
homeworkTicketList.add(new HomeworkTicket("2", "王五", "未完成"));
Map<String, List<HomeworkTicket>> groupedHomeworkTicketList = homeworkTicketList.stream()
.collect(Collectors.groupingBy(HomeworkTicket::getId));
System.out.println(groupedHomeworkTicketList);
}
}
输出结果:
{1=[HomeworkTicket@2f4d3709, HomeworkTicket@7440e464], 2=[HomeworkTicket@49476842]}
阅读全文