Java List<实体类> 单字段,多字段去重,条件过滤

业务代码

import com.shsnc.perform.vo.Student;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class EntityUtil {


    public static void main(String[] args) {
        List stuList = new ArrayList<>();
        stuList.add(new Student(1, "tome", 10, "京爷"));
        stuList.add(new Student(2, "jack", 20, "沪爷"));
        stuList.add(new Student(3, "lucy", 30, "津爷"));
        stuList.add(new Student(4, "tome", 40, "沪爷"));
        stuList.add(new Student(5, "any", 50, "京爷"));
        stuList.add(new Student(5, "any", 50, "京爷"));

        System.out.println("init 初始化");
        for (Student student : stuList) {
            System.out.println(student);
        }

        // 取出 List  集合中 name 作为 list
        System.out.println("集合中 name 作为 list");
        List nameList = stuList.stream().map(Student::getName).collect(Collectors.toList());
        System.out.println(nameList);


        // 过滤集合中 名称重复的数据  单个字段重复时过滤
        System.out.println("过滤集合中 名称重复的数据, name字段重复数据会过滤掉");
        List studentList1 = stuList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new)
        );
        for (Student student : studentList1) {
            System.out.println(student);
        }

        // 根据某字段过滤
        System.out.println(" 查询集合中 地址等于 “京爷” 并且 age > 10 的数据");
        List studentList2 = stuList.stream().filter(student -> student.getAddress().equals("京爷") && student.getAge() > 10).collect(Collectors.toList());
        for (Student student : studentList2) {
            System.out.println(student);
        }

        System.out.println(" 整个对象字段完全相同去重");
        List studentList3 = stuList.stream().distinct().collect(Collectors.toList());
        for (Student student : studentList3) {
            System.out.println(student);
        }

    }

}

实体类

import lombok.Data;

@Data
public class Student {

    Integer id;
    String name;
    Integer age;
    String address;

    public Student(Integer id, String name, Integer age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }
}

结果

Java List<实体类> 单字段,多字段去重,条件过滤_第1张图片

 

你可能感兴趣的:(java,list,jvm)