Learn how to find numbers starting with 1 in Java 8 using Stream API , filter() , String.valueOf(), startsWith(), and Collectors.toList() with a simple example.
Code Explanation (Step-by-Step):
• Create a list using Arrays.asList() .
• Convert the list into a Stream using stream() .
• Convert each number to a String using String.valueOf().
• Use startsWith(“1”) inside filter() to find matching numbers.
• Collect the result using Collectors.toList().
• Print the filtered numbers.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 4, 45, 120, 67, 31, 140, 561, 100);
List result = numbers.stream()
.filter(num -> String.valueOf(num).startsWith("1"))
.collect(Collectors.toList());
System.out.println("Numbers starting with 1: " + result);
}
}
Output :
Numbers starting with 1 : [1, 120, 140, 100]
Filter Numbers Using startsWith()
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 4, 45, 120, 67, 31, 140, 561, 100);
List result = numbers.stream()
.map(String::valueOf)
.filter(num -> num.startsWith("1"))
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println("Numbers starting with 1: " + result);
}
}
Output :
Numbers starting with 1: [1, 120, 140, 100]
FAQ
How do you find numbers starting with 1 in Java 8?
Convert each number to a String using String.valueOf() and use startsWith(“1”) inside the Stream filter() method.
Why is String.valueOf() used in this example?
The startsWith() method is available for Strings only, so integers must be converted into strings before checking their starting digit.
Which Stream method is used for filtering?
The filter() method is used to select only those numbers that satisfy the specified condition.