Java Reference
In-Depth Information
5.1.2. Filtering unique elements
Streams also support a method called distinct that returns a stream with unique elements
(according to the implementation of the hashCode and equals methods of the objects produced
by the stream). For example, the following code filters all even numbers from a list and makes
sure that there are no duplicates. Figure 5.2 shows this visually:
Figure 5.2. Filtering unique elements in a stream
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct()
.forEach(System.out::println);
5.1.3. Truncating a stream
Streams support the limit(n) method, which returns another stream that's no longer than a
given size. The requested size is passed as argument to limit. If the stream is ordered, the first
elements are returned up to a maximum of n. For example, you can create a List by selecting the
first three dishes that have more than 300 calories as follows:
List<Dish> dishes = menu.stream()
 
Search WWH ::




Custom Search