从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序:
1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35
package com.sc.test;
import java.io.*;
import java.util.*;
/**
* @Author 邓德春
* @Date 2020/1/9 18:32
* @Description
*/
public class Name_test {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("d:/ddd.txt"));
String s = reader.readLine();
List<String> list = new ArrayList<>();
while (s!=null){
String[] aa = s.split(",");
list.add(aa[1]);
s = reader.readLine();
}
Set<String> set = new HashSet<>(list);
Map map = new HashMap();
for(String bb:set){
map.put(bb, Collections.frequency(list, bb));
}
List<Map.Entry<String,Integer>> list1 = new ArrayList<>(map.entrySet());
Collections.sort(list1, 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();
}
});
for(Map.Entry m : list1){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}