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:

@Test
public 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 filters the input and returns a value without all the elements filtered out. Using lambdas makes the code elegant and really easy to read.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.134.17