filter

Let's start with the filter operation. Filters is a function with a self-explanatory name; it filters in/out elements in the stream depending on whether the value satisfies a condition, as shown in the following example:

@Testpublic void filterByNameReturnsCollectionFiltered() {  List<String> names = Arrays.asList("Alex", "Paul", "Viktor",         "Kobe", "Tom", "Andrea");  List<String> filteredNames = Collections.emptyList();  assertThat(filteredNames)      .hasSize(2)      .containsExactlyInAnyOrder("Alex", "Andrea");}

One possibility for computing the list of filteredNames is the following:

List<String> filteredNames = names.stream()      .filter(name -> name.startsWith("A"))      .collect(Collectors.toList());

That one is the easiest. In a few words, filter ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.