Java-如何打印名称和排序日期? [英] Java-How to Print names along with sorted dates?

查看:91
本文介绍了Java-如何打印名称和排序日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称和DateOfbirths的文件.我将BateOfBirths与正则表达式匹配,我想将它们存储到数组中,以便可以对日期进行排序.我所做的是
文字档:

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

我的代码:

    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

推荐答案

您只需创建一个ArrayList并将其存储在其中即可.

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());
    }
}

要记住的一件事是您计划对它们进行排序.您可能可以使用String比较器和Collections.sort(birthDates)逃脱.如果需要Date对象,则可以使用m.group()并将其解析为Date对象.然后,只需将您的ArrayList类型更改为ArrayList<Date>.

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>.

如果确实需要将其作为数组,则可以使用List界面中的.toArray(T[])进行更改.

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()]);

这篇关于Java-如何打印名称和排序日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆