184. Matching elements in a stream

To match certain elements in a Stream, we can rely on the following methods:

  • anyMatch()
  • noneMatch()
  • allMatch()

All of these methods take a Predicate as an argument and fetch a boolean result against it.

These three operations rely on the short-circuiting technique. In other words, these methods may return until we process the entire stream. For example, if allMatch() matches false (evaluates the given Predicate as false), then there is no reason to continue. The final result is false.

Let's assume that we have the following list wrapped in a stream:

List<String> melons = Arrays.asList(
"Gac", "Cantaloupe", "Hemi", "Gac", "Gac", "Hemi",
"Cantaloupe", "Horned", "Hemi", "Hemi");

Now, let's try to answer the following questions:

  • Does an element match the Gac string? Let's see that in the following code:
boolean isAnyGac = melons.stream()
.anyMatch(m -> m.equals("Gac")); // true
  • Does an element match the Apollo string? Let's see that in the following code:
boolean isAnyApollo = melons.stream()
.anyMatch(m -> m.equals("Apollo")); // false

As a general question – is there an element in the stream that matches the given predicate?

  • Do no elements match the Gac string? Let's see that in the following code:
boolean isNoneGac = melons.stream()
.noneMatch(m -> m.equals("Gac")); // false
  • Do no elements match the Apollo string? Let's see that in the following code:
boolean isNoneApollo = melons.stream()
.noneMatch(m -> m.equals("Apollo")); // true

As a general question – are there no elements in the stream that match the given predicate?

  • Do all the elements match the Gac string? Let's see that in the following code:
boolean areAllGac = melons.stream()
.allMatch(m -> m.equals("Gac")); // false
  • Are all the elements larger than 2? Let's see that in the following code:
boolean areAllLargerThan2 = melons.stream()
.allMatch(m -> m.length() > 2);

As a general question—do all the elements in the stream match the given predicate?

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

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