一、Stream去重的介紹
在Java 8以後,引入了一個非常強大的流處理(Stream)庫,其中一個流操作是去重。Stream去重是一種便捷的方法,用於刪除集合中的重複元素並返回一個新的無重複元素的流。
Stream去重可以用於各種類型的集合,包括List, Set, 數組等。
下面是一個Java 8的Stream去重示例:
<pre><code>List<String> strings = Arrays.asList("a", "b", "c", "a", "d", "b");
List<String> distinctStrings = strings.stream().distinct().collect(Collectors.toList());</code></pre>
在上述示例中,我們創建了一個字符串列表,其中包含重複元素。我們可以使用distinct()方法來獲取一個新的沒有重複元素的流。
值得注意的是,Stream去重操作返回的流是有序的,並且保留了原始流中的元素順序。
二、Stream去重的方法
1.使用distinct方法去重
Java 8的Stream API提供了一個distinct()方法,可以去除流中的重複元素。
<pre><code>List<String> strings = Arrays.asList("a", "b", "c", "a", "d", "b");
List<String> distinctStrings = strings.stream().distinct().collect(Collectors.toList());</code></pre>
2.利用Set去重
利用Set去重是一種簡單而有效的方法。由於Set是一個不允許重複元素的集合,我們可以先將集合轉換成Set,再將Set轉換回集合即可去掉重複元素。
<pre><code>List<String> strings = Arrays.asList("a", "b", "c", "a", "d", "b");
List<String> distinctStrings = new ArrayList<>(new HashSet<>(strings));</code></pre>
3.利用HashMap去重
利用HashMap去重是一種比較常見的做法。我們可以將集合中的元素作為HashMap的key,這樣就會自動去重。
<pre><code>List<String> strings = Arrays.asList("a", "b", "c", "a", "d", "b");
List<String> distinctStrings = new ArrayList<>(new HashMap<>().keySet());</code></pre>
三、Stream去重的性能
在集合較小的情況下,三種去重方式的性能差別不大。但在處理大型集合時,使用HashMap去重通常是最快的方式,因為它使用了哈希表的快速查找特性。
下面是一個對Java 8 Stream去重進行性能測試的示例:
<pre><code>List<Integer> integers = new Random().ints().limit(100000).boxed().collect(Collectors.toList());
long startTime = System.nanoTime();
List<Integer> distinctIntegers1 = new ArrayList<>(new HashSet<>(integers));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("HashSet duration: " + duration);
startTime = System.nanoTime();
List<Integer> distinctIntegers2 = integers.stream().distinct().collect(Collectors.toList());
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("Stream distinct duration: " + duration);
startTime = System.nanoTime();
List<Integer> distinctIntegers3 = new ArrayList<>(new HashMap<>().keySet());
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("HashMap duration: " + duration);</code></pre>
在上述示例中,我們創建了一個包含10萬個整數的隨機列表,然後計算HashSet、Stream distinct和HashMap去重操作的持續時間。在我的測試中,HashMap的處理速度遠遠快於其他兩種方式。
四、Stream去重的總結
Stream去重是Java 8中非常有用的一個方法,它能夠輕鬆地從任何集合中刪除重複元素。在實現Stream去重時,我們可以利用Java 8 Stream API提供的distinct()方法、Set或HashMap等方法。在處理大型集合時,使用HashMap去重通常是最快的方式。
原創文章,作者:TYGIE,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/371455.html