从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,按重复次数排序: (编程, 提示:集合)

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.TreeSet;

public class demo_03 {

    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream("D:/name.txt")));

        String line = null;
        
        HashMap<String , Integer> nameAndAges = new HashMap<>();
        
        while( (line = br.readLine()) != null)
        {
            System.out.println(line);
            String[] infos = line.split("    ");
            
            String name = infos[0];
            String age = infos[1];
            
            if(nameAndAges.containsKey(name))
            {
                nameAndAges.put(name, nameAndAges.get(name)+1);
            }else
            {
                nameAndAges.put(name, 1);
            }
        }
        
        //不需要准备TreeMap了,只需要准备TreeSet就可以了
        TreeSet<InfoClass> ageAndNames = new TreeSet<>();
        
        for (String name : nameAndAges.keySet()) {
            
            InfoClass info = new InfoClass();
            info.setName(name);
            info.setCount(nameAndAges.get(name));
            ageAndNames.add(info);
            
        }
        
        for (InfoClass info : ageAndNames) {
            
            System.out.println(info.getCount() + " "+ info.getName());
            
        }
        
    }

}

class InfoClass implements Comparable<InfoClass>
{
    private String name;
    private int count;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    @Override
    public String toString() {
        return "InfoClass [name=" + name + ", count=" + count + "]";
    }
    
    
    @Override
    public int compareTo(InfoClass o) {
        
        if(this.count > o.count)
        {
            return 1;
        }else if(this.count < o.count){
            return -1;
        }else{//次数一样,比较名字
            return this.name.compareTo(o.name);
        }

        
    }
    
    
}

猜你喜欢

转载自www.cnblogs.com/hryh/p/10233131.html