Selecting Distinct Elements – Streams
Selecting Distinct Elements
The distinct() method removes all duplicates of an element from the input stream, resulting in an output stream with only unique elements. Since the distinct() method must be able to distinguish the elements from one another and keep track of them, the stream elements must override the equals() and the hashCode() methods of the Object class. The CD objects comply with this requirement (Example 16.1, p. 883).
In Figure 16.4, Query 2 creates a list of unique CDs with pop music. The filter() operation and the distinct() operation in the stream pipeline select the CDs with pop music and those that are unique, respectively. The execution of the stream pipeline shows that the resulting list of unique CDs with pop music has only one CD (cd0).
In Figure 16.4, interchanging the stateless filter() operation and the stateful distinct() operation in the stream pipeline gives the same results, but then the more expensive distinct() operation is performed on all elements of the stream, rather than on a shorter stream which is returned by the filter() operation.
Figure 16.4 Selecting Distinct Elements
Skipping Elements in a Stream
The skip() operation slices off or discards a specified number of elements from the head of a stream before the remaining elements are made available to the next operation. It preserves the encounter order if the input stream has one. Not surprisingly, skipping more elements than are in the input stream returns the empty stream.
In Figure 16.5, Query 3a creates a list of jazz music CDs after skipping the first two CDs in the stream. The stream pipeline uses a skip() operation first to discard two CDs (one of them being a jazz music CD) and a filter() operation afterward to select any CDs with jazz music. The execution of this stream pipeline shows that the resulting list contains two CDs (cd3, cd4).
In the stream pipeline in Figure 16.5, the skip() operation is before the filter() operation. Switching the order of the skip() and filter() operations as in Query 3b in Example 16.5 does not solve the same query. It will skip the first two jazz music CDs selected by the filter() operation.
Figure 16.5 Skipping Elements at the Head of a Stream
Archives
- July 2024
- June 2024
- May 2024
- March 2024
- February 2024
- January 2024
- December 2023
- October 2023
- September 2023
- May 2023
- March 2023
- January 2023
- December 2022
- November 2022
- October 2022
- September 2022
- August 2022
- July 2022
- April 2022
- March 2022
- November 2021
- October 2021
- September 2021
- July 2021
- June 2021
- March 2021
- February 2021
Calendar
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |