亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 關注
  • 406 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號