面试题5

从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:
1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.maoge;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class {
public static void main(String args[]) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("D:\IDEA\workspace\file\info.txt"));

Map map = new HashMap();

for (String line : lines) {
dealLine(map, line);
}

sortResult(map);
}

static class User {
public String name;
public int value;

public User(String name, int value) {
this.name = name;
this.value = value;
}

}

public static void dealLine(Map map, String line) {
if (!"".equals(line.trim())) {
String[] info = line.split(",");
String name = info[1];
Integer value = (Integer) map.get(name);
if (value == null) value = 0;
map.put(name, value + 1);
}
}

("unchecked")
public static void sortResult(Map map) {
TreeSet set = new TreeSet(
new Comparator() {
@Override
public int compare(Object o1, Object o2) {
User u1 = (User) o1;
User u2 = (User) o2;
if (u1.value < u2.value) {
return -1;
} else if (u1.value > u2.value) {
return 1;
} else {
return u1.name.compareTo(u2.name);
}
}
}
);

Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String name = (String) iterator.next();
Integer value = (Integer) map.get(name);
if (value > 1) {
set.add(new User(name, value));
}
}

printResults(set);

}

public static void printResults(TreeSet set) {
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
User user = (User) iterator.next();
System.out.println(user.name + " " + user.value);
}
}
}

limaodeng

scribble