Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Java program to check if none of the string in the list matches the condition
In this article, you will learn how to check if none of the strings in a list start with a specific letter using Java. This approach is useful for validating or filtering data. We will use the Stream API to evaluate the condition and return a boolean result based on whether any string starts with the given letter.
Problem Statement
Write a program in Java to check if none of the strings in the list matches the condition.
Input
pqr,stu,vwx,yza,vwxy<br>
Output
No match for the starting letter as f? = true<br>
Steps to check if none of the string matches the condition
Following are the steps to check if none of the string matches the condition
- First, we will import ArrayList and List from the java.util package.
- Create a list using the ArrayList class, we will create a list of strings.
- Use the Stream API by calling the stream() method to work with the list as a stream.
- Apply the noneMatch() method by using noneMatch() to check if none of the strings start with the specified letter.
- At the end, the boolean result will be printed to the console.
Java program to check if none of the string matches the condition
The following is an example to check if none of the string in the list matches the condition
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(final String[] args) {
List<String> myList = new ArrayList<>();
myList.add("pqr");
myList.add("stu");
myList.add("vwx");
myList.add("yza");
myList.add("bcd");
myList.add("efg");
myList.add("vwxy");
boolean res = myList.stream().noneMatch((a) -> a.startsWith("f"));
System.out.println("No match for the starting letter as f? = "+res);
}
}
Output
No match for the starting letter as f? = true
Code explanation
In the above program, we create a list of strings using the ArrayList class and populate it with several string values. The stream() method is called on the list, enabling us to use the noneMatch() method from the Stream API. This method checks if none of the strings in the list start with the letter 'f'. If this condition holds true for all elements, the method returns true; otherwise, it returns false. The result is then printed to the console, showing whether any string starts with 'f'.
