In this article, we will discuss Stream’s allMatch() method in details with examples.
Read below methods which are similar to allMatch() method
1. Stream allMatch() method :
- This Stream method is a terminal operation which returns true if all the elements of the given Stream satisfies the provided Predicate, otherwise returns false
- But even if one of the elements in the original Stream doesn’t matches the given Predicate then it will return false
- Stream’s allMatch() method is stateless which means it is non-interfering with other elements in the stream
- May not evaluate the predicate on all elements if not necessary for determining the result
- It is a short-circuiting terminal operation, as Stream pipeline ends for the non-match of the provided Predicate
- If the stream is empty then true is returned and the predicate is not evaluated
- Method signature :- boolean allMatch(Predicate<? super T> predicate)
2. Stream allMatch() method examples :
2.1 To evaluate different Predicate for the Integer list
- A list contains integer numbers from 1 to 10
- 1st Predicate – checks whether all number are positive // returns true
- 2nd Predicate – checks whether all number are greater than 10 // returns true
- 3rd Predicate – checks whether all numbers are divisible by 2 // returns false
- 4th Predicate – checks whether all numbers are divisible by 3 // returns false
package net.bench.resources.stream.allmatch.example;
import java.util.Arrays;
import java.util.List;
public class StreamAllMatchMethodForInteger {
public static void main(String[] args) {
// list of 10 natural numbers
List<Integer> numbers = Arrays
.asList(1,2,3,4,5,6,7,8,9,10);
System.out.println("Original list of integers : " + numbers);
// 1. predicate to check all number are positive ?
boolean isPositive = numbers
.stream()
.allMatch(num -> num > 0);
System.out.println("\n1. All numbers are positive = "
+ isPositive);
// 2. predicate to check all number are greater than 10 ?
boolean isGreaterThan10 = numbers
.stream()
.allMatch(num -> num > 0);
System.out.println("\n2. All numbers are greater than 10 = "
+ isGreaterThan10);
// 3. predicate to check all number are divisible by 2 ?
boolean isDivisibleBy2 = numbers
.stream()
.allMatch(n-> n % 2 == 0);
System.out.println("\n3. All numbers are divisible by 2 = "
+ isDivisibleBy2);
// 4. predicate to check all number are divisible by 3 ?
boolean isDivisibleBy3 = numbers
.stream()
.allMatch(n-> n % 3 == 0);
System.out.println("\n4. All numbers are divisible by 3 = "
+ isDivisibleBy3);
}
}
Output:
Original list of integers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1. All numbers are positive = true
2. All numbers are greater than 10 = true
3. All numbers are divisible by 2 = false
4. All numbers are divisible by 3 = false
2.2 To evaluate different Predicate for the list of Strings
- A list contains String elements
- 1st Predicate – verifies whether all String’s length is greater than 4 // returns true
- 2nd Predicate – checks whether all String’s first character is in Upper Case // returns true
- 3rd Predicate – checks whether all String’s last character is in Lower Case // returns true
- 4th Predicate – checks whether all Strings contains any Digits // returns false
- 5th Predicate – checks whether all Strings contains only characters // returns true
package net.bench.resources.stream.allmatch.example;
import java.util.Arrays;
import java.util.List;
public class StreamAllMatchMethodForString {
public static void main(String[] args) {
// list of 5 Strings
List<String> sectors = Arrays.asList(
"Motor",
"Power",
"Steel",
"Chemicals",
"Capital"
);
System.out.println("Original list of Strings : " + sectors);
// 1. predicate - all String elements length greater than 4
boolean isStrLengthGreaterThan4 = sectors
.stream()
.allMatch(str -> str.length() > 4);
System.out.println("\n1. All String - length greater than 4 ? "
+ isStrLengthGreaterThan4);
// 2. predicate - 1st character is in upperCase
boolean isFirstCharInUpperCase = sectors
.stream()
.allMatch(str -> Character.isUpperCase(str.charAt(0)));
System.out.println("\n2. All String - 1st character is in upperCase ? "
+ isFirstCharInUpperCase);
// 3. predicate - last character is in upperCase
boolean isLastCharInLowerCase = sectors
.stream()
.allMatch(str -> Character.isLowerCase(str.charAt(str.length()-1)));
System.out.println("\n3. All String - last character is in lowerCase ? "
+ isLastCharInLowerCase);
// 4. predicate - String contains digits
boolean isContainDigits = sectors
.stream()
.allMatch(str -> str.matches("\\d+"));
System.out.println("\n4. All String contains digits ? "
+ isContainDigits);
// 5. predicate - String matches all characters
boolean isMatchesCharacter = sectors
.stream()
.allMatch(str -> str.matches("[A-Za-z]+")); // \\d+
System.out.println("\n5. All String - matches only characters ? "
+ isMatchesCharacter);
}
}
Output:
Original list of Strings : [Motor, Power, Steel, Chemicals, Capital]
1. All String - length greater than 4 ? true
2. All String - 1st character is in upperCase ? true
3. All String - last character is in lowerCase ? true
4. All String contains digits ? false
5. All String - matches only characters ? true
2.3 To find Students from multiple Predicates
- A Student POJO is defined with 3 attributes
- A list contains 5 Student objects defining their attributes like rollNumber, name, and age
- We have defined 2 simple Predicate namely p1 and p2 and one more joined Predicate which is the combined Predicate of p1 && p2
- 1st Predicate – checks whether all Students name contains character ‘i‘ // returns true
- 2nd Predicate – checks whether all Students age is greater than or equal to 16 // returns true
- 3rd Predicate – checks whether all Students name contains character ‘i‘ and age is greater than or equal to 16 // returns true
- 4th Predicate – checks whether all Students name starts with ‘V‘ and age is less than or equal to 16 // returns false
Student.java
package net.bench.resources.stream.anymatch.example;
public class Student {
// member variables
private int rollNumber;
private String name;
private int age;
// constructors
public Student(int rollId, String name, int age) {
super();
this.rollNumber = rollId;
this.name = name;
this.age = age;
}
// getters & setters
public int getRollId() {
return rollNumber;
}
public void setRollId(int rollId) {
this.rollNumber = rollId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// toString()
@Override
public String toString() {
return "Student [rollNumber=" + rollNumber
+ ", name=" + name
+ ", age=" + age
+ "]";
}
}
StreamAllMatchMethodForStudents.java
package net.bench.resources.stream.allmatch.example;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import net.bench.resources.stream.min.max.example.Student;
public class StreamAllMatchMethodForStudents {
public static void main(String[] args) {
// list of students
List<Student> students = Arrays.asList(
new Student(1, "Viraj", 17),
new Student(2, "Krishnanand", 18),
new Student(3, "Rishi", 16),
new Student(4, "Nair", 23),
new Student(5, "Aditya", 21)
);
// predicate 1 - name contains 'i'
Predicate<Student> p1 = stud -> stud.getName().contains("i");
// predicate 2 - age older than or equal to 16
Predicate<Student> p2 = stud -> stud.getAge() >= 16;
// combined predicate - p1 && p2
Predicate<Student> p3 = p1.and(p2);
// print all Students to console
System.out.println("List of Students :-");
students.stream().forEach(student -> System.out.println(student));
// 1. find whether all Student name contains 'i'
boolean isContainsAlphai = students.stream().anyMatch(p1);
System.out.println("\n1. Whether all Student's name"
+ " contains character 'i' ? "
+ isContainsAlphai);
// 2. find whether all Student age is older/Equal to 16
boolean isAgeGreaterEqualTo16 = students.stream().anyMatch(p2);
System.out.println("\n2. Whether all Student's Age"
+ " greater than or Equal to 16 ? "
+ isAgeGreaterEqualTo16);
// 3. Student name contains 'i' && age is older/Equal to 16
boolean isContainsiAndAge16 = students.stream().anyMatch(p3);
System.out.println("\n3. Whether all Student's Name"
+ " contains 'i' and Age greater than or Equal to 16 ? "
+ isContainsiAndAge16);
// 4. Student name starts with 'V' && age is less/Equal to 15
boolean isNameStartsWithVAndAge15 = students.stream().anyMatch(
stud -> (stud.getName().startsWith("V") && stud.getAge() <= 15));
System.out.println("\n4. All Student's Name starts with 'V' "
+ "and Age less than or Equal to 15 present ? "
+ isNameStartsWithVAndAge15);
}
}
Output:
List of Students :-
Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krishnanand, age=18]
Student [rollNumber=3, name=Rishi, age=16]
Student [rollNumber=4, name=Nair, age=23]
Student [rollNumber=5, name=Aditya, age=21]
1. Whether all Student's name contains character 'i' ? true
2. Whether all Student's Age greater than or Equal to 16 ? true
3. Whether all Student's Name contains 'i' and Age greater than or Equal to 16 ? true
4. All Student's Name starts with 'V' and Age less than or Equal to 15 present ? false
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Happy Coding !!
Happy Learning !!