Java 进行词频统计,并按单词顺序顺序排序

本文针对以前一篇的博客 java进行文本单词的词频统计 进行补充,在统计文本词频之后,又对map按key值进行排序,即按单词顺序排序。

package com.cute.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SortMapTest {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new FileReader("F:/test/source.txt"));
		List<String> lists = new ArrayList<String>(); // 存储过滤后单词的列表
		String readLine = null;
		while ((readLine = br.readLine()) != null) {
			String[] wordsArr1 = readLine.split("[^a-zA-Z]"); // 过滤出只含有字母的
			for (String word : wordsArr1) {
				if (word.length() != 0) { // 去除长度为0的行
					lists.add(word);
				}
			}
		}

		br.close();

		Map<String, Integer> wordsCount = new TreeMap<String, Integer>(); // 存储单词计数信息,key值为单词,value为单词数

		// 单词的词频统计
		for (String li : lists) {
			if (wordsCount.get(li) != null) {
				wordsCount.put(li, wordsCount.get(li) + 1);
			} else {
				wordsCount.put(li, 1);
			}

		}

		// 对map利用key排序
		Map<String, Integer> resMap = sortMapByKey(wordsCount);

		for (Entry<String, Integer> entry : resMap.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}

	/**
	 * 让 Map按key进行排序
	 */
	public static Map<String, Integer> sortMapByKey(Map<String, Integer> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map<String, Integer> sortMap = new TreeMap<String, Integer>(new MapKeyComparator());
		sortMap.putAll(map);
		return sortMap;
	}
}

// 实现一个比较器类

class MapKeyComparator implements Comparator<String> {

	@Override
	public int compare(String s1, String s2) {
		return s1.compareTo(s2); // 从小到大排序
	}
}

输出结果:


基咯咯  767696856


  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Halo 咯咯

有你的支持我会更加努力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值