从一个文件中统计字符出现的次数并且进行排序取出前5条

思路:用hashmap 中的键 表示某个字符,有value表示出现的次数,然后按照value值进行排序。

          用value值进行排序,就要把map转化成list

         然后用Collectios.sort(list,comparator)进行排序

1.1要统计的文件位置如下

1.2 要统计的文件内容如下

errlog

22
22
22
22
22
222
11
22
33
1
4
5
7
8
9
10
11
111
33
44
555
66
77
99
99
110

 

2.1

代码如下

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package test16;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

public class TxtTest {
    public TxtTest() {
    }

    public static void txt2String(File file) {
        HashMap hashMap = new HashMap();
        try {
//读取文件 BufferedReader br
= new BufferedReader(new FileReader(file)); String s = null; while((s = br.readLine()) != null) { int i = (new Integer(s)).intValue(); if (!hashMap.containsKey(i)) { hashMap.put(i, Integer.valueOf(1)); } else { int value = ((Integer)hashMap.get(i)).intValue(); ++value; hashMap.put(i, value); } } br.close(); } catch (Exception var8) { var8.printStackTrace(); }
//排序 List
<Entry<Integer, Integer>> list = new ArrayList(); list.addAll(hashMap.entrySet()); Collections.sort(list, new Comparator<Entry<Integer, Integer>>() { public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) { return ((Integer)o2.getValue()).intValue() - ((Integer)o1.getValue()).intValue(); } });

//输出前5行
int i = 0; for(Iterator iterator = list.iterator(); iterator.hasNext() && i < 5; ++i) { Entry entry = (Entry)iterator.next(); int key = ((Integer)entry.getKey()).intValue(); int value = ((Integer)entry.getValue()).intValue(); System.out.println(value + "个 " + key); } } public static void main(String[] args) { URL url = Thread.currentThread().getContextClassLoader().getResource(""); url.getPath(); File file = new File(url.getPath() + "test16//errlog"); txt2String(file); } }

 3.1运行结果

posted @ 2017-11-10 10:30  huanglei2010  阅读(1304)  评论(1)    收藏  举报