There are following way to find out all the numbers starting with 1 using java8 Stream functions.
- First convert Arrays to list using Arrays.asList() method.
- Now get the Stream data from List using arrayList.stream() method.
- Inside filter we call to startsWith() method to check if a string starts with the given prefix.
- Now call the Collectors.toList() to store all number inside list.
- From Collectors.toList() method we are collect all elements which start with 1.
- print the number.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<Integer> number = Arrays.asList(1, 4, 45, 120, 67, 31, 140, 561, 100);
List<Integer> listNum = number.stream().filter(d -> String.valueOf(d).startsWith("1"))
.collect(Collectors.toList());
System.out.println("find out all the numbers starting with 1 :- " + listNum);
}
}
Output :-
find out all the numbers starting with 1 :- [1, 120, 140, 100]