代碼去重

1.list  對象依據某一屬性去重  代碼中Student爲對象,屬性則爲id與name。代碼依據id去除id相同的Student實體。

import java.util.*;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class Test {

    public static void main(String[] args) {
        Student s1 = new Student();

        s1.setId(1);
        s1.setName("aaaa");

        Student s2 = new Student();
        s2.setId(2);
        s2.setName("bbbb");

        Student s3 = new Student();
        s3.setName("cccc");
        s3.setId(3);
        Student s4 = new Student();
        s4.setName("ddd");
        s4.setId(4);
        Student s5 = new Student();
        s5.setId(1);
        s5.setName("eee");

        List<Student> list = Arrays.asList(s1,s2,s3,s4,s5);
        List<Student> s = test2(list);
        System.out.println(Arrays.toString(s.toArray()));

    }

    //對象去重
    public static List<Student> test2(List<Student> list){
        List<Student> unique = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingInt(Student::getId))), ArrayList::new)
        );

        return unique;
    }
}

 2.list  對象依據多個屬性去重

import java.util.*;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class Test {

    public static void main(String[] args) {
        Student s1 = new Student();

        s1.setId(1);
        s1.setName("aaaa");

        Student s2 = new Student();
        s2.setId(2);
        s2.setName("bbbb");

        Student s3 = new Student();
        s3.setName("cccc");
        s3.setId(3);
        Student s4 = new Student();
        s4.setName("ddd");
        s4.setId(4);
        Student s5 = new Student();
        s5.setId(1);
        s5.setName("aaaa");

        List<Student> list = Arrays.asList(s1,s2,s3,s4,s5);
        List<Student> s = test2(list);
        System.out.println(Arrays.toString(s.toArray()));

    }

    //對象去重
    public static List<Student> test2(List<Student> list){
        List<Student> unique = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparing(s->s.getId()+";"+s.getName()))), ArrayList::new)
        );

        return unique;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章