应用场景
在项目开发的过程中,我们经常会对List集合进行按条件的过滤,筛选出我们想要的结果或者是符合项目需求的数据。比如:我们有一批学生对象,每个学生都有自己的性别属性,但是我们想要再班级实体中筛选出这一批学生中性别为男或女的学生,我们就需要对这一批学生集合中的数据进行按条件的筛选,得到我们想要的结果。(多表连接:双向映射)
学生实体类
public class Student implements Serializable { private int id; private String name; private String sex; private String hobbies; private Integer bj; private TSmClazz clazz; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "BJ", insertable = false, updatable = false) @NotFound(action = NotFoundAction.IGNORE) @JsonIgnoreProperties(value = "students") public TSmClazz getClazz() { return clazz; } public void setClazz(TSmClazz clazz) { this.clazz = clazz; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", unique = true, nullable = false) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name = "SEX") public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Column(name = "HOBBIES") public String getHobbies() { return hobbies; } public void setHobbies(String hobbies) { this.hobbies = hobbies; } @Column(name = "BJ") public Integer getBj() { return bj; } public void setBj(Integer bj) { this.bj = bj; }
使用Java8中的lambda表达式过滤
返回集合:
ModelMap model = new ModelMap(); TSmClazz TSmClazz = tSmClazzService.get(id); List<Student> students = TSmClazz.getStudents(); if(flag.equals("0")){ List<Student> boys =students.stream().filter(s->s.getSex().equals("0")).collect(Collectors.toList()); model.put("data", boys); }else if(flag.equals("1")){ List<Student> girls =students.stream().filter(s->s.getSex().equals("1")).collect(Collectors.toList()); model.put("data", girls); }else{ model.put("data", students); }
或单体类:
goodsKind = goodsKindList.stream().filter(s->s.getId().equals(storeGoods.getKindNext())).collect(Collectors.toList()).get(0);
前端显示
标签:TSmClazz,java,String,void,List,集合,return,public,name From: https://www.cnblogs.com/Fooo/p/17273177.html