Sebastian Zeki
Sebastian Zeki

Reputation: 6874

Reordering array into arrayList at a certain position

I am trying to reformat some strings that are dates. Some of them have the year at the beginning and I would like those to have their year be at the end. I also want to standardize the separator character to an underscore.

Example input:

07_April_2008
16_05_2012
2016-01-28
14/12/2009

Desired output:

07_April_2008
16_05_2012
01_28_2016
14_12_2009

Here's my first attempt, , but I get an error when I do this:

public String format(String date) {
    String[] format = null;
    date = date.replace("-", "_");
    date = date.replace("/", "_");
    if (date.contains("_")) {
        format = date.split("_");
        // new arrayList to add rearrangement to
        ArrayList<String> formatNew = new ArrayList<String>();
        for (int i = 0; i < format.length; i++) {
            if (format[i].matches("\\d{4}")) {
                formatNew.add(2, format[i]);
            } else {
                formatNew.add(format[i]);
            }
        }
    }
    return date;
}

This produces the error:

java.lang.IndexOutOfBoundsException: Index: 2, Size: 0

I think the year is being picked up fine but the other two elements in the array not.

Upvotes: 3

Views: 98

Answers (2)

Bohemian
Bohemian

Reputation: 425198

I would approach it as a String problem:

List<String> dates; // given this
dates = dates.stream()
    .map(s -> s.replaceAll("\\W", "_")) // anything not a letter or number becomes _
    .map(s -> s.replaceAll("(\\d{4})_(.*)", "$2_$1")) // reorganise leading year dates
    .collect(Collectors.toList());

If you just want to format a date string:

str.replaceAll("\\W", "_").replaceAll("(\\d{4})_(.*)", "$2_$1")

If you want to preserve the separator (only changed to underscore to make your code work):

str.replaceAll("(\\d{4})(.)(.*)", "$3$2$1")

Upvotes: 1

Saravana
Saravana

Reputation: 12817

From Java doc

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Below is ArrayList.add(index,E) method source code

public void add(int index, E element) {
if (index > size || index < 0)
    throw new IndexOutOfBoundsException(
    "Index: "+index+", Size: "+size);
...

so it is clear, if the index is greater than the size or negative it will throw IndexOutOfBoundsException.

Have a look at the DateFormatUtils it has many standard date formats, with that you can format dates

Upvotes: 1

Related Questions