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)
返回其元素是指定值的順序排序流。
返回由通過將提供的映射函數應用於每個元素而產生的映射流的內容來替換該流的每個元素的結果的流。
