1.从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,并按重复次数排序
注意自己在编辑文本的时候,一定要注意自己编辑文本的txt 文件要这是字符集,否则容易出错,要和你eclise 的字符集一致
1.对于读取文件,大家要熟记BufferedReader类,他可以一次读取一行,在很多的笔试题会遇到这样的例子,但是判断读取结束的标志并不是我们平时所见的-1,而是null。
2.可以利用集合进行简化代码,比如list元素可以重复,但是set的元素不可以重复等
name.txt文件内容如下
1,张三,28
2,李四,35
3,张三,28
4,王五,35
5,张三,28
6,李四,35
7,赵六,28
8,田七,35
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Test { public static void main(String[] args) throws Exception { HashMap<String,Integer> map=new HashMap<String, Integer>(); BufferedReader br=new BufferedReader( new InputStreamReader(new FileInputStream("C:\\Users\\Administrator\\Desktop\\427.txt"),"utf-8")); String lines=null; while((lines=br.readLine())!=null){ String user=lines; String[] userArry=user.split(","); if(map.containsKey(userArry[1])){ map.put(userArry[1], map.get(userArry[1])+1); }else{ map.put(userArry[1], 1); } } Set<String> nameSet=new HashSet<String>(); for (String key : map.keySet()) { nameSet.add(key); } System.out.println("所有的用户:"+nameSet); HashMap<String,Integer> chongfumap=new HashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : map.entrySet()) { if(entry.getValue()>1){ chongfumap.put(entry.getKey(), entry.getValue()); } } System.out.println("重复map:"+chongfumap); // 升序比较器 Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() { public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return o1.getValue()-o2.getValue(); } }; // map转换成list进行排序 List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(chongfumap.entrySet()); // 排序 Collections.sort(list,valueComparator); System.out.println("排序开始"); for (Map.Entry<String, Integer> entry : list) { System.out.println(entry.getKey() + ":" + entry.getValue()); } System.out.println("排序结束"); } }