Problem:
Given a list of strings, how do you filter only those strings that start with a digit using Java 8 Streams?
✅Example:
import java.util.Arrays;
import java.util.List;
public class StringStartingWithNumber {
public static void main(String[] args) {
List<String> list = Arrays.asList("TOrange", "Banana", "2Papaya", "Grapes", "3Pineapple", "Cherry");
list.stream()
.filter(str -> !str.isEmpty() && Character.isDigit(str.charAt(0)))
.forEach(System.out::println);
}
}
✅Output:
2Papaya
3Pineapple
✅Explanation:
- We define a list of strings:
["TOrange", "Banana", "2Papaya", "Grapes", "3Pineapple", "Cherry"]
- We create a stream from the list:
list.stream()
- The
filter()
condition:str -> !str.isEmpty() && Character.isDigit(str.charAt(0))
- Ensures the string is not empty.
- Checks whether the first character is a digit using
Character.isDigit(str.charAt(0))
.
- The filtered strings are printed using:
forEach(System.out::println);