從類似如下的文字檔案中讀取出所有的姓名,並打印出重複的姓名和重複的次數,按重複次數排序: (程式設計, 提示:集合)
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);
}
}
}