猿问

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

我是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();

            }


我该怎么做?


皈依舞
浏览 360回答 3
3回答

守着星空守着你

您可以做的是您可以Comparable在您的接口中实现接口Patient并覆盖该compareTo方法。这样,当 Collections 的 sort 方法被调用时,它会使用你的 compareTo 方法进行比较。

心有法竹

假设那些是字符串,使用方便的静态方法sort......&nbsp;java.util.Collections.sort(patients)

一只甜甜圈

对于字符串,这将起作用: arrayList.sort((p1, p2) -> p1.compareTo(p2));&nbsp;(Java 8)
随时随地看视频慕课网APP

相关分类

Java
我要回答