1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class AnswerB06 {
public static void main(String[] args) throws IOException {
Map<String, Integer> nameMap = new HashMap<String, Integer>();
BufferedReader reader = new BufferedReader(new InputStreamReader(AnswerB06.class.getResourceAsStream("/person.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
String[] segments = line.split(",", -1);
String name = segments[1];
Integer count = nameMap.get(name);
if (count == null) {
count = 0;
}
count++;
nameMap.put(name, count);
}
reader.close();
List<PersonCount> personCounts = new ArrayList<PersonCount>();
Set<String> names = nameMap.keySet();
for (String name : names) {
PersonCount personCount = new PersonCount();
personCount.name = name;
personCount.count = nameMap.get(name);
personCounts.add(personCount);
}
Collections.sort(personCounts);
for (PersonCount personCount : personCounts) {
System.out.println(personCount.name + "=" + personCount.count);
}
}
static class PersonCount implements Comparable<PersonCount> {
public String name;
public int count;
@Override
public int compareTo(PersonCount o) {
return count - o.count;
}
}
}