Write a Java program using Lambda Expression to check if all strings in a list start with the letter "S"


The Java program you provided checks if all strings in a list start with the letter 'S' (uppercase) or 's' (lowercase) using Java Streams and the allMatch method. Here's an explanation of the code:

  • An ArrayList named strings is created to store a list of strings.
  • System.out.println("Given String : " + strings); prints the original list of strings.
  • The program uses Java Streams to check if all strings in the list start with 'S' or 's':
    • strings.stream(): This converts the strings list into a stream of strings.
    • .allMatch(s -> s.startsWith("S") || s.startsWith("s")): This checks if all elements in the stream satisfy the condition that the string starts with either 'S' or 's'. If all elements satisfy this condition, it returns true, indicating that all strings start with 'S' or 's. Otherwise, it returns false.
  • The program stores the result in the allStartWithS variable.
  • It then uses an if statement to check the value of allStartWithS. If allStartWithS is true, it prints "All strings start with 'S' or 's'". If allStartWithS is false, it prints "Not all strings start with 'S' or 's'".

Source Code

import java.util.ArrayList;
import java.util.List;
 
public class StringStartWithS
{
	public static void main(String[] args)
	{
		List<String> strings = new ArrayList<>();
		strings.add("sugar Apple");
		strings.add("Sapodilla Fruit");
		strings.add("Strawberry");
		strings.add("salmonberry");
 
		System.out.println("Given String : " + strings);
 
		boolean allStartWithS = strings.stream().allMatch(s -> s.startsWith("S") || s.startsWith("s"));
 
		if (allStartWithS)
		{
			System.out.println("All strings start with 'S' or 's'");
		}
		else
		{
			System.out.println("Not all strings start with 'S' or 's'");
		}
	}
}

Output

Given String : [sugar Apple, Sapodilla Fruit, Strawberry, salmonberry]
All strings start with 'S' or 's'

Example Programs