将score.txt的数据读取到集合中,根据学生学号统计总成绩,对总成绩降序排序后输出前十名
score.txt文件数据:学号,科目,成绩
代码如下:
package IO流;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("JavaSE/src/IO流/stu_data/score.txt"));
// 读
String line;
while ((line = br.readLine()) != null) {
// 切分行数据
String[] splits = line.split(",");
// 对行数据做脏数据判断
if (splits.length == 3) {
// 学号 成绩
String id = splits[0];
int score = Integer.parseInt(splits[2]);
// 如果已经存在这个学号
if (hashMap.containsKey(id)) {
// 学号,总成绩(相加上个科目成绩)
hashMap.put(id, hashMap.get(id) + score);
} else {
// 学号,成绩
hashMap.put(id, score);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
// 排序
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue(); // 总成绩降序排序
}
});
// 遍历输出前十个
Iterator<Map.Entry<String, Integer>> iterator = list.iterator();
for (int i = 0; i < 10; i++) {
if (iterator.hasNext()) {
Map.Entry<String, Integer> next = iterator.next();
System.out.println("学号:" + next.getKey() + "\t总分:" + next.getValue());
}
}
}
}
运行结果如下: