Java-How to Print names along with sorted dates?

2019-09-03 14:29发布

问题:

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

回答1:

You can just create an ArrayList and store them in there.

List<String> birthDates = new ArrayList<String>();
Pattern datePattern = Pattern.compile("\\d\\d-\\d\\d-\\d\\d\\d\\d");
for(String name : names) {
    Matcher m = datePattern.matcher(name);
    while(m.find()) {
        birthDates.add(m.group());
    }
}

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 a Date object, you can use m.group() and parse it into a Date object. Then, simply change your ArrayList type to be ArrayList<Date>.

Edit: If you really need it to be an array, you can then use the .toArray(T[]) in the List interface to change it.

String[] birthDatesArray = birthDates.toArray(new String[birthDates.size()]);


回答2:

You can do this:

while (mat.find()) {
    System.out.println(mat.group());
}

Edited

I'm sorry I didn't notice your question. To save results:

import java.util.*;

...

List<String> matches = new ArrayList<String>();
while (mat.find()) {
    matches.add(mat.group());
}