Home > Back-end >  How to get numbers that have the same first 4 digits into List in Java
How to get numbers that have the same first 4 digits into List in Java

Time:06-06

I would like to get the numbers that start with 2003 (2003001 and 2003002) and put them in another list.

public static void main(String[] args) {

    String [] num = {"2012001", "2003001", "2003002"};
    List<String> list = new ArrayList<String>();
    for(String actualList : num) {
        list.add(actualList);
    }
}

CodePudding user response:

You can use the startsWith() method:

String[] num = {"2012001", "2003001", "2003002"};

List<String> list = new ArrayList<>();

for (String number : num) {
    if (number.startsWith("2003")) {
        list.add(number);
    }
}

CodePudding user response:

Besides @Adixe iterative solution, you could concisely achieve that also with streams by streaming the array, filtering for the elements starting with 2003 and the collecting the remaining elements with the terminal operation collect(Collectors.toList()).

String[] num = {"2012001", "2003001", "2003002"};
List<String> listNums = Arrays.stream(num)
        .filter(s -> s.startsWith("2003"))
        .collect(Collectors.toList());
  • Related