List collection ----- use Stream to remove duplicate entries

Java8 removed using Stream Interface between duplicate set

 

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 to use the content of the collection is not repeated de-emphasis

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

② to re-use the Stream interfaces

 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)

Sequential ordering elements are returned to their specified flow value.
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns the content stream by mapping by the mapping function provided to each element generated by replacing each element of the results of the flow stream.
 

Guess you like

Origin www.cnblogs.com/JMrLi/p/11271709.html