主要分两部分:
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());
}
}
}