從類似如下的文本文件中讀取出所有的姓名,並打印出重復的姓名和重復的次數,並按重復次數排序


文件格式如下: 

1,s,28
2,a,35
3,a,28
4,b,35
5,s,28
6,a,35
7,c,28
8,d,35
9,c,28
10,c,28
11,c,28
12,c,28
13,c,28

代碼的思路如下: 

首先取出每行的內容,並放入一個list中,然后取出每一行的name分別放入set和list中,計算出重復的個數,最后進行排序。

package jisuan;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StringTest {

    public static void main(String[] args) throws Exception {
        InputStreamReader is = new FileReader("C:\\test\\b.txt");
        BufferedReader br = new BufferedReader(is);
        List<String> list = new ArrayList<String>();
        String str = "";
        // 讀取文件,把取出的每一行放入到list中
        while ((str = br.readLine()) != null) {
            list.add(str);
        }
        // 使用set存放name 不包括重復,使用list 存放所有的name
        Set<String> set = new HashSet<String>();
        List<String> listname = new ArrayList<String>();
        for (String s : list) {
            String[] sa = s.split(",");
            set.add(sa[1]);
            listname.add(sa[1]);
        }
        // 獲取重復name的數目
        List<P> Plist = new ArrayList<P>();
        
        for (String setstr : set) {
            int count = 0;
            for (int j = 0; j < listname.size(); j++) {

                if (setstr.equals(listname.get(j))) {
                    count++;
                }
            }
            if (count > 1) {
                Plist.add(new P(count, setstr));
                // 這個是對於Comparable 接口的
                Collections.sort(Plist);
            }
        }
        for (P p : Plist) {
            System.out.println(p.count + "===" + p.name);
        }

    }
}

// 創建一個類,並排序
class P implements Comparable<P> {
    int count;

    String name;

    public P(int count, String name) {
        this.count = count;
        this.name = name;
    }

    @Override
    public int compareTo(P o) {
        if (this.count > o.count) {
            return 1;
        } else {
            return -1;
        }
    }

}
輸出的結果是:
2===s
3===a
6===c

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM