背景介绍:
在ESB项目迁移中,遇到过滤数据的需求,这里使用Java代码stream().filter()实现。
解决方案:
参考代码如下:
public Student(String name, String age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", sex='" + sex + '\'' + '}';
}
主函数:
public static void main(String[] args) {
Student student1 = new Student("11", "11", "0");
Student student2 = new Student("11", "22", "1");
Student student3 = new Student("11", "22", "0");
Student student4 = new Student("11", "33", "1");
Student student5 = new Student("22", "33", "0");
List<Student> students = new ArrayList();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
System.out.println("--------------------对象去重-----------------------");
List<Student> collect = students.stream().distinct().collect(toList());
for (Student student : collect) {
System.out.println(student);
}
System.out.println("-------------------根据多个字段去重--------------------------");
ArrayList<Student> collect1 = students.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(student -> student.getName() + student.getAge()))), ArrayList::new));
for (Student student : collect1) {
System.out.println(student);
}
System.out.println("-------------------根据多个字段条件过滤筛选--------------------------");
List<Student> filterCollect = students.stream().filter(s -> Objects.equals(s.getName(), "11") && Objects.equals(s.getSex(), "0")).collect(Collectors.toList());
for (Student student : filterCollect) {
System.out.println(student);
}
评论前必须登录!
注册