我是Java初学者。我需要按字母顺序对一串名称进行排序。我有一个类从文本文件中读取并写入按年龄(小于 18 岁)过滤的排序文件,但我需要它按字母顺序过滤,下面是我的实现。它在没有按名称过滤的情况下工作正常。 public class PatientFileProcessor { public void process(File source, File target) { System.out.println("source"+source.getAbsolutePath()); System.out.println("target"+target.getAbsolutePath()); try { writefile(target, filterbyAge(readfile(source))); } catch (Exception ex) { Logger.getLogger(PatientFileProcessor.class.getName()).log(Level.SEVERE, null, ex); } } public List<Patient> readfile(File source) throws Exception { List<Patient> patients = new ArrayList(); BufferedReader bf = new BufferedReader(new FileReader(source)); String s = bf.readLine();// ignore first line while ((s = bf.readLine()) != null) { String[] split = s.split("\\|"); System.out.println(Arrays.toString(split)); System.out.println(s+" "+split[0]+" "+split[1]+" "+split[2]); Date d = new SimpleDateFormat("yyyy-dd-MM").parse(split[2]); patients.add(new Patient(split[0], split[1], d)); } return patients; } public void writefile(File target, List<Patient> sorted) throws Exception { BufferedWriter pw = new BufferedWriter(new FileWriter(target)); DateFormat df = new SimpleDateFormat("yyyy/dd/MM"); for (Iterator<Patient> it = sorted.iterator(); it.hasNext();) { Patient p = it.next(); pw.append(p.getName() + "|" + p.getGender() + "|" + df.format(p.getDob())); pw.newLine(); } pw.flush(); }我该怎么做?
3 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
您可以做的是您可以Comparable
在您的接口中实现接口Patient
并覆盖该compareTo
方法。这样,当 Collections 的 sort 方法被调用时,它会使用你的 compareTo 方法进行比较。
添加回答
举报
0/150
提交
取消