统计文字中的单词数量并按出现次数排序(Java--map的值排序与键排序)

主要分两部分:
1.先对输入单词进行处理:
使用map接口,单词为键,出现次数为值
用字符串内部方法替换掉单词中的特殊符号
根据单词是否重复,从而向写入新的键值对或者增加单词(键)对应的出现次数(值)

2.再对构造的map对象进行类型转换:
个人理解(具体原理可自行学习Map.Entry<K, V>和Map.entrySet()):把键值对看作一个整体,这个整体就是list中元素的具体类型,然后把map变成list,就可以自己写list的比较方法了

3.最后写一个继承comparator的类,重写compare方法,用该方法实现Collections.sort(),对list排序即可

import java.util.*;
import java.util.Map.Entry;

public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Map<String, Integer> words = new TreeMap<String, Integer>();
		String input;
		while(true) {
			input = sc.next();
			if(input.equals("!!!!!")) {
				break;
			}
			input = input.toLowerCase().replaceAll("[!.,:*?]", "");
			if(words.get(input)==null) {
				words.put(input, 1);
			}
			else {
				int times = words.get(input);
				words.put(input, ++times);
			}
		}
		System.out.println(words.size());
		Iterator it;
		List<Map.Entry<String, Integer>> change = new ArrayList<Map.Entry<String, Integer>>(words.entrySet());
		Collections.sort(change,new mapValueandKeyCompare());
		int flag=0;
		for(it=change.iterator();it.hasNext();) {
			flag++;
			System.out.println(it.next());
			if (flag==10) {
				break;
			}
		}
	}
}
class mapValueandKeyCompare implements Comparator<Map.Entry<String, Integer>>{

	@Override
	public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
		if(o1.getValue()>o2.getValue()) {
			return -1;
		}
		else if(o1.getValue()<o2.getValue()) {
			return 1;
		}
		else {
			return o1.getKey().compareTo(o2.getKey());
		}
	}
	
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值