Filter Strings Starting with a Number

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:

  1. We define a list of strings: ["TOrange", "Banana", "2Papaya", "Grapes", "3Pineapple", "Cherry"]
  2. We create a stream from the list: list.stream()
  3. 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)).
  4. The filtered strings are printed using: forEach(System.out::println);

Java developer with 9+ years of IT experience, sharing tutorials and tips to help learners master Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *