Sebastian Zeki Sebastian Zeki - 6 months ago 7
Java Question

Reordering array into arrayList at a certain position

I am trying to reformat some dates. Some of them have the year at the beginning and I would like them to be at the end, and some of them don't. As a first attempt I would like to put the years, where they have 4 numbers to be at the end of an arrayList (further manipulation to follow). I seem to get an error when I do this
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


My attempt:

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 ends in 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

Answer

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")
Comments