从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序,文本内容如下:
1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35
-
package com.wp;
-
-
-
import java.io.*;
-
import java.util.*;
-
-
public class GetNameCount {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) throws IOException{
-
// TODO Auto-generated method stub
-
-
//两种读文件的方式
-
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:\\java\\infor.txt")));
-
//InputStream ips = GetNameCount.class.getResourceAsStream("infor.txt");
-
//BufferedReader br = new BufferedReader(new InputStreamReader(ips));
-
-
String line=null;
-
-
Map<String,Integer> results=new HashMap<String,Integer>();
-
-
try{
-
while((line=br.readLine())!=null)
-
{
-
dealLine(line,results);
-
}
-
sortResults(results);
-
-
}catch(IOException e){
-
e.printStackTrace();
-
}
-
}
-
-
public static void dealLine(String line,Map<String,Integer> map)
-
{
-
if(!"".equals(line.trim()))//出去字符处的前导空格,防止不必要的空格导致错误
-
{
-
String [] results =line.split(",");
-
if(results.length == 3)
-
{
-
String name = results[1];
-
Integer value =(Integer)map.get(name);
-
-
if(value ==null)
-
value = 0;
-
-
map.put(name,value + 1);
-
}
-
}
-
}
-
-
static class User
-
{
-
public String name;
-
public Integer value;
-
-
public User(String name,Integer value){
-
this.name = name;
-
this.value = value;
-
}
-
@Override
-
public boolean equals(Object obj) {
-
// TODO Auto-generated methodstub
-
//下面的代码没有执行,说明往treeset中增加数据时,不会使用到equals方法。
-
boolean result =super.equals(obj);
-
System.out.println(result);
-
return result;
-
}
-
}
-
-
-
private static void sortResults(Map<String,Integer> results) {
-
// TODO Auto-generated method stub
-
@SuppressWarnings("unchecked")
-
TreeSet<User> sortedResults =new TreeSet<User>(new Comparator(){
-
-
public int compare(Object o1, Object o2) {
-
// TODOAuto-generated method stub
-
User user1 = (User)o1;
-
User user2 = (User)o2;
-
/*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去
-
* 所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。
-
* */
-
//returnuser1.value-user2.value;
-
//returnuser1.value
-
if(user1.value<user2.value){
-
return -1;
-
}else if(user1.value>user2.value){
-
return 1;
-
}else{
-
return user1.name.compareTo(user2.name);
-
}
-
}
-
} );
-
-
Iterator iterator =results.keySet().iterator();
-
-
while(iterator.hasNext())
-
{
-
String name = (String)iterator.next();
-
Integer value =(Integer)results.get(name);
-
-
if(value >= 1)
-
{
-
sortedResults.add(new User(name,value));
-
}
-
}
-
printResults(sortedResults);
-
}
-
-
private static void printResults(TreeSet<User> sortedResults)
-
{
-
Iterator iterator = sortedResults.iterator();
-
while(iterator.hasNext())
-
{
-
User user = (User)iterator.next();
-
System.out.println(user.name +":" + user.value);
-
}
-
}
-
-
}
阅读(876) | 评论(0) | 转发(0) |