从一个文件中统计字符出现的次数并且进行排序取出前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运行结果

转载于:https://www.cnblogs.com/huanglei2010/articles/7813287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值