list对象根据项目编号projectNo字段去重 Java8 并且过滤出状态为going的项目
假设项目类为Project,有projectNo和status两个字段。
首先需要创建一个List
示例代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// 创建项目列表
List<Project> projectList = new ArrayList<>();
projectList.add(new Project("001", "going"));
projectList.add(new Project("002", "going"));
projectList.add(new Project("001", "completed"));
projectList.add(new Project("003", "going"));
// 去重并过滤状态为going的项目
List<Project> filteredList = projectList.stream()
.filter(project -> project.getStatus().equals("going"))
.distinct()
.collect(Collectors.toList());
// 打印结果
for (Project project : filteredList) {
System.out.println(project.getProjectNo() + " " + project.getStatus());
}
}
static class Project {
private String projectNo;
private String status;
public Project(String projectNo, String status) {
this.projectNo = projectNo;
this.status = status;
}
public String getProjectNo() {
return projectNo;
}
public String getStatus() {
return status;
}
}
}
输出结果为:
001 going
002 going
003 going
注意:上述代码假设状态字段status为String类型,如果是枚举类型或其他类型,请根据实际情况修改代码
原文地址: https://www.cveoy.top/t/topic/iyhW 著作权归作者所有。请勿转载和采集!