stream流处理List对象集合去重

stream流处理List对象集合去重

public class TestStream {

    //创建一个list对象包含student对象 根据id去重
    private static  List<Student> list = new ArrayList<>();
    static {
        Student s1 = new Student("1", "老大");
        Student s2 = new Student("1", "老二");
        Student s3 = new Student("2", "老三");
        list.add(s1);
        list.add(s2);
        list.add(s3);
    }

    public static void main(String[] args) {
        ArrayList<Student> collect1 = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getId))), ArrayList::new));
        collect1.forEach(x-> System.out.println(x.getId()+"-"+x.getName()));

    }
}

stream流处理List对象集合去重_第1张图片

你可能感兴趣的:(java)