Posts

Showing posts with the label Java8StreamAllMatch

Stream API AllMatch in Java 8 with examples

In this blog post, I will be demonstrating the allMatch method provided by Java 8 Stream API. Edit In order to understand the Stream API in detail, refer to  this  blog post. Code Sample with Integer You can use the  allMatch method to determine if all the elements in a Collection matches a particular condition. Consider the following code snippet: public class AllMatchIntegerDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); boolean found = input.stream().allMatch(num -> num % 2 == 0); System.out.println("All even numbers: "+found); }} This code checks if all the numbers in the input stream are even. First, the code obtains a  Stream  on the input ArrayList using the  stream() method. Then the code invokes the  allMatch method on the stream instance. This method accepts a  Predicate  instance.  Predicate  is an in-built functional interface.  Refer  this  blog post for a detailed  Predic...