package am;
/*
* 从类似如下的文本文件中读取出所有的姓名,并打印出重复的
* 姓名和重复的次数,并按重复次数排序:
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CopyOfGetNameTest
{
public static void main(String[] args)
{
Map<String,Integer> results = new TreeMap<String,Integer>();
List<User> tm = new ArrayList<User>();
tm.add(new User("张三", 28));
tm.add(new User("李四", 35));
tm.add(new User("张三", 28));
tm.add(new User("王五", 35));
tm.add(new User("张三", 28));
tm.add(new User("李四", 35));
tm.add(new User("赵六", 28));
tm.add(new User("田七", 35));
for(User x:tm)
{
dealLine(x,results);
}
for(Map.Entry<String, Integer> m:results.entrySet())
{
System.out.println(m);
}
}
private static void dealLine(User x, Map<String, Integer> map)
{
String name = x.getName();
Integer value = (Integer) map.get(name);
if(value == null)
{
value = 0;
}
map.put(name, value + 1);
}
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);
}
}
}
}
class User implements Comparable<User>
{
public String name;
public Integer value;
public User(String name,Integer value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public Integer getAge()
{
return value;
}
@Override
public String toString()
{
return "name = " + name + " value = " + value;
}
@Override
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if(obj instanceof User)
{
User user = (User) obj;
if((this.name.equals(user.name)) && (this.value == user.value))
{
return true;
}
}
return false;
}
public int compareTo(User user)
{
int num = 0;
int i = this.name.compareTo(user.name);
if(i>0)
{
num = 1;
}
else if(i<0)
{
num = -1;
}
else
{
num = this.value>user.value?1:(this.value==user.value?0:-1);
}
return num;
}
}