打印出重复的姓名和重复的次数,并按重复次数排序:
生活随笔
收集整理的這篇文章主要介紹了
打印出重复的姓名和重复的次数,并按重复次数排序:
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
讀取文件內(nèi)容,
打印出重復(fù)的姓名和重復(fù)的次數(shù),并按重復(fù)次數(shù)排序:?
package com;import java.io.*; import java.util.*;/* 打印出重復(fù)的姓名和重復(fù)的次數(shù),并按重復(fù)次數(shù)排序:*/ public class Demo05 {public static void main(String[] args) throws Exception {BufferedReader br = new BufferedReader(new FileReader("d:/co.txt"));List<String> list = new ArrayList<>();String str = "";//將讀取的名字添加到list中while ((str = br.readLine()) != null){list.add(str);}//定義map存儲(chǔ)名字和個(gè)數(shù)。Map<String,Integer> hMap = new HashMap<>();for (String s:list) {//取名字String[] mid = s.split(","); // System.out.println(mid[1]);if (hMap.get(mid[1]) == null){hMap.put(mid[1],1);}else{hMap.put(mid[1],hMap.get(mid[1]) + 1);}} // System.out.println(hMap);List<Integer> times = new ArrayList<>();//遍歷mapSet<Map.Entry<String,Integer>> eSet = hMap.entrySet();//將map的value值取出存儲(chǔ)到times集合中for (Map.Entry<String,Integer> e : eSet) {System.out.println(e);Integer value = e.getValue();times.add(value);}//對(duì)序號(hào)進(jìn)行排序Collections.sort(times);System.out.println(times);//遍歷序號(hào)for (Integer i : times) {for (Map.Entry<String,Integer> e : eSet) {//如果序號(hào)和map中的value一致則輸出,但需注意重復(fù),輸出后,清除這個(gè)元素,并break跳出循環(huán)//避免后面循環(huán)中的重復(fù)數(shù)據(jù)if (i == e.getValue()){System.out.println(e.getKey() + e.getValue());//查出一個(gè)后刪除,并退出,為了避免重復(fù)輸出eSet.remove(e);break;}}}//關(guān)閉流br.close();} }?
總結(jié)
以上是生活随笔為你收集整理的打印出重复的姓名和重复的次数,并按重复次数排序:的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 截取字符串,但要保证汉字不被截取半个
- 下一篇: 一个整数按照n,2n,4n,8n的顺序递