I have a file with names and DateOfbirths. I am matching the BateOfBirths with the regex and i want to store them into an array so that i can sort dates. What i have done is
Text file:
name1 dd-MM-yyyy
name2 dd-MM-yyyy
namw3 dd-MM-yyyy
name4 dd-MM-yyyy
my code:
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
import java.util.*;
import java.text.*;
class SortDate{
public static void main(String args[]) throws IOException {
BufferedReader br=new BufferedReader(new FileReader("dates.txt"));
File file = new File("dates.txt");
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
count++;
}
String[] names= new String[count];
List<Date> birthDates = new ArrayList<Date>();
for(int x=0;x<count;x++)
{
names[x]=br.readLine();
}
String Dates="\\d\\d-\\d\\d-\\d\\d\\d\\d";
Pattern pat=Pattern.compile(Dates);
for(String s:names){
try {
Matcher mat=pat.matcher(s);
while(mat.find()){
String str=mat.group();
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str);
birthDates.add(date);
}
}catch (ParseException e)
{System.out.println("Exception :"+e); } }
Collections.sort(birthDates);
System.out.println(names+birthDates);
}}
I am able to print the sorted dates but how can i print the names along with the dates. thanks
You can just create an
ArrayList
and store them in there.One thing to keep in mind is that you plan on sorting these. You can probably get away with using the String comparator and using
Collections.sort(birthDates)
. In the case that you need aDate
object, you can usem.group()
and parse it into aDate
object. Then, simply change yourArrayList
type to beArrayList<Date>
.Edit: If you really need it to be an array, you can then use the
.toArray(T[])
in theList
interface to change it.You can do this:
Edited
I'm sorry I didn't notice your question. To save results: