Stream.distinct() 在 Java 中
stream 類的 distinct() 方法返回包含此流的不同元素的流。語法如下 -
Stream<T> distinct()
示例
以下是實現 Stream 類中 distinct() 方法的示例 -
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
System.out.println("List = "+list);
System.out.println("Displaying only the distinct elements = ");
list.stream().distinct().forEach(System.out::println);
}
}輸出
List = [10, 30, 40, 40, 50, 70, 90, 90, 100] Displaying only the distinct elements = 10 30 40 50 70 90 100
示例
我們來看看另一個示例 -
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
System.out.println("List = "+list);
System.out.println("Count of distinct elements = "+(list.stream().distinct().count()));
System.out.println("Displaying only the distinct elements = ");
list.stream().distinct().forEach(System.out::println);
}
}輸出
List = [10, 30, 40, 40, 50, 70, 90, 90, 100] Count of distinct elements = 7 Displaying only the distinct elements = 10 30 40 50 70 90 100
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP