To print all words in a string list that starting and ending with same character using Java 8, we can use the Stream API with the filter() method.
- First, we create a list of strings.
- Then, we convert the list into a stream using stream().
- Next, we use the filter() method to select only those words whose first and last characters are the same.
- Finally, we print the matching words using the forEach() method.
import java.util.Arrays;
import java.util.List;
public class StartAndEndSameChar {
public static void main(String[] args) {
List list = Arrays.asList("abc", "mnm", "xyx",
"wer", "aba");
list.stream().filter(e -> e.length() > 0 &&
e.endsWith(String.valueOf(e.charAt(0)))).
forEach(System.out::println);
}
}
Output :-
mnm
xyx
aba