List集合----利用Stream接口合並和去除重復項


Java8 利用Stream接口去除集合間重復項

 

java.util.stream

Public Interface Stream<T>

extends BaseStream<T,Stream<T>>

 

        Student s1 = new Student(1,20,"Bob");
        Student s2 = new Student(2,20,"Jim");
        Student s3 = new Student(3,20,"Tom");
        Student s4 = new Student(4,20,"Jack");

        List<Student> listC = new ArrayList<>();
        listC.add(s1);
        listC.add(s2);
        listC.add(s3);
        List<Student> listD = new ArrayList<>();
        listC.add(s1);
        listC.add(s2);
        listC.add(s4);    

① 使用 Set 集合的 內容不重復進行去重

 Set<Student> set = new HashSet<>(listC);
        set.addAll(listD);
        List<Student> list = new ArrayList<Student>(set);
        System.out.println(list);

② 使用 Stream 接口 進行去重

 List<Student> studentList = Stream.of(listC,listD).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        System.out.println(studentList);

 

static <T> Stream<T> of(T... values)

返回其元素是指定值的順序排序流。
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
返回由通過將提供的映射函數應用於每個元素而產生的映射流的內容來替換該流的每個元素的結果的流。
 

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM