Learn how to check if a List Contains an Uppercase String in Java8 using Stream API and anyMatch() with a simple example.
Code Explanation (Step-by-Step)
- Create a list of strings using Arrays.asList() .
- Convert the list into a stream using stream().
- Use the anyMatch() method to evaluate each element.
- Convert each string to uppercase using toUpperCase().
- Compare the original string with its uppercase version using equals().
- If at least one string matches, anyMatch() returns true.
- Print the Boolean type of output status.
import java.util.Arrays;
import java.util.List;
public class MatchTest {
public static void main(String[] args) {
List listString = Arrays.asList(
"hibernate",
"JAVA",
"spring",
"servlet",
"jsp",
"123"
);
boolean status = listString.stream()
.anyMatch(e -> e.matches("[A-Z]+"));
System.out.println("Uppercase word is there :- " + status);
}
}
Output :
Uppercase word is there :- true
Java 8 Program to Find Uppercase Words Using Stream API
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FindUppercaseWords {
public static void main(String[] args) {
List listString = Arrays.asList(
"hibernate",
"JAVA",
"spring",
"SERVLET",
"jsp",
"123"
);
List upperCaseWords = listString.stream()
.filter(str -> str.equals(str.toUpperCase()) &&
str.matches("[A-Za-z]+"))
.collect(Collectors.toList());
System.out.println(upperCaseWords);
}
}
Output :
[JAVA, SERVLET]
Here are some related Java 8 programs that will help you understand Stream API concepts better: