Print Words That Start and End With Same Letter in Java 8

Learn how to print words that start and end with same letter in Java 8 using Stream API, filter(), and collect() methods with example and explanation.

Code Explanation point wise

  • Arrays.asList() method creates a list of String values.
  • list.stream() converts the list into a stream for processing data.
  • word.length() > 0 ensures that the string is not empty and contains at least one character.
  • word.charAt(0) retrieves the first character of the string.
  • String.valueOf(word.charAt(0)) converts the first character into a String.
  • word.endsWith(String.valueOf(word.charAt(0))) checks whether the string ends with the same character as its first character.
  • collect(Collectors.toList()) collects all matching strings into a new List.
  • Now print all words that start and end with same characters.
				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SameWord {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("abc", "aba", "xyz", "sta", "pap");

        List<String> letter = list.stream()
                .filter(word -> word.length() > 0 &&
                        word.endsWith(String.valueOf(word.charAt(0))))
                .collect(Collectors.toList());

        System.out.println("Start and End with same letter are :- " + letter);
    }
}
``
				
			

Output :
Start and End with same letter are :- [aba, pap]

Java 8 Program to Print all the words in a string which starts and ends with same letter

				
					import java.util.Arrays;

public class SameLetterWords {
    public static void main(String[] args) {

        String str = "level java radar spring madam stream refer";

        Arrays.stream(str.split("\\s+"))
              .filter(word -> !word.isEmpty() &&
                      Character.toLowerCase(word.charAt(0)) ==
                      Character.toLowerCase(word.charAt(word.length() - 1)))
              .forEach(System.out::println);
    }
}
				
			

Output :
level
radar
madam
refer

FAQ
Which Stream method is used to filter words?
The filter() method is used to select words that satisfy the condition.
Can this program work with a sentence instead of a list?
Yes. First split the sentence into words using split(“\\s+”), then process the words using a stream.
How do we get the first and last character of a string?
Using charAt(0) and charAt(length – 1).
Can this program ignore case sensitivity?
Yes, by converting the string to lowercase before comparison.
Can I perform a case-insensitive comparison?
Yes. Convert both characters to lowercase or uppercase before comparing them.
Character.toLowerCase(word.charAt(0)) ==
Character.toLowerCase(word.charAt(word.length() – 1))