为了账号安全,请及时绑定邮箱和手机立即绑定

如何在java中按字母顺序对字符串列表进行排序?

如何在java中按字母顺序对字符串列表进行排序?

皈依舞 2021-10-27 09:52:33
我是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 方法进行比较。


查看完整回答
反对 回复 2021-10-27
?
心有法竹

TA贡献1866条经验 获得超5个赞

假设那些是字符串,使用方便的静态方法sort......

 java.util.Collections.sort(patients)


查看完整回答
反对 回复 2021-10-27
?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

对于字符串,这将起作用: arrayList.sort((p1, p2) -> p1.compareTo(p2)); (Java 8)


查看完整回答
反对 回复 2021-10-27
  • 3 回答
  • 0 关注
  • 359 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信