Home > Enterprise >  Filter out the elements that Start with given 4 digit and store them into a List
Filter out the elements that Start with given 4 digit and store them into a List

Time:06-06

I would like to get the numbers that start with 2003 (2003001 and 2003002) and put them into 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());

CodePudding user response:

As @Ole V.V. has pointed out in the comments, it seems like strings in your arrays are comprised of the year like 2012 and the day of the year like 001.

If so, it would be match more convenient to convert this data into LocalDate than operating with it as if it's a plain string.

To parse this row string into LocalDate you need to create a DateTimeFormatter using the static method ofPattern(). A string pattern that corresponds to the sample data will be:

yyyyDDD

y - stands for year

D - day of the year

For more information see

So to filter out dates having a particular year, firstly we need to parse strings using LocalDate.parse() by passing the string and the formatter as argument, and then extract year from each date by applying getYear():

String [] num = {"2012001", "2003001", "2003002"};
        
int targetYear = 2003;
    
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyDDD");
        
List<LocalDate> dates = Arrays.stream(num)
    .map(date -> LocalDate.parse(date, formatter)) 
    .filter(date -> date.getYear() == targetYear)
    .collect(Collectors.toList());
    
System.out.println(dates);

Output:

[2003-01-01, 2003-01-02]
  • Related