O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required