文章目录
前言
在开发的过程中,我们或许会遇到对数组对象中,某一特殊属性进行查重功能,一下将针对三种情况来提供不同的解决方案,愿此文将对你有所帮助。
一、前期准备
1.创建实体
关于枚举的实现可阅读本文,链接: Enum实现.
@Data
@Table
@Entity
public class Student {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid",strategy = "org.hibernate.id.UUIDGenerator")
private String id;
private String name;
private Sex sex;
private int age;
}
二、出现场景:
场景一:根据某一属性进行查重分类
1.代码如下
@PostMapping("check")
public Map<Integer, List<Student>> checkRepetition() throws Exception {
List<Student> studentList = studentRepo.findAll();
Map<Integer, List<Student>> map = new HashMap<>();
try {
for (Student student : studentList) {
if (map.containsKey(student.getAge())) { // 存在age,则添加
map.get(student.getAge()).add(student);
} else {
List<Student> sList = new ArrayList<>();
sList.add(student);
map.put(student.getAge(),sList);
}
}
} catch (Exception e) {
throw new Exception("分组时出现异常", e);
}
return map;
}
}
2.查询结果如下
场景二:根据某一属性查重并返回成树形数据
1.在返回对象中添加children,如下
/**
* 用于返回tree型数据
*/
private List<Student> children = new ArrayList<>();
2.代码如下
@PostMapping("check-tree")
public Map<Integer, Student> checkRepetitionForTree() throws Exception {
List<Student> studentList = studentRepo.findAll();
Map<Integer, Student> map = new HashMap<>();
try {
for (Student student : studentList) {
if (map.containsKey(student.getAge())) { // 存在age,则添加至同一个key下
Student s = map.get(student.getAge());
if (s != null) {
s.getChildren().add(student);
}
} else {
map.put(student.getAge(),student);
}
}
} catch (Exception e) {
throw new Exception("分组时出现异常", e);
}
return map;
}
3.查询结果如下
4.拓展:使用场景
此种情况适用于开发树形表格功能
,具体前端实现参考Element官方文档
链接: Element 组件 树形数据与懒加载.