Find Numbers Starting with the digit ‘1’

Problem:
Given a list of integers (which may contain null values), filter out all the numbers that start with the digit '1' using Java 8 Streams.

✅Example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NumbersStartingWithOne {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(123, null, null, 345, 765, 1876, 90, 100);

        List<Integer> numbersStartingWithOne = numbers.stream()
                .filter(num -> num != null && String.valueOf(num).startsWith("1"))
                .collect(Collectors.toList());

        numbersStartingWithOne.forEach(System.out::println);
    }
}

✅ Example Output:

123
1876
100

✅ Explanation:

  • The list of numbers is: [123, null, null, 345, 765, 1876, 90, 100].
  • We use numbers.stream() to create a stream.
  • The filter() condition: num -> num != null && String.valueOf(num).startsWith("1")
    • Skips null values to avoid NullPointerException.
    • Converts the number to a string and checks if it starts with '1'.
  • .collect(Collectors.toList()) collects the filtered numbers into a new list.
  • Finally, numbersStartingWithOne.forEach(System.out::println); prints: 123 1876 100

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 *