package test;
import java.text.Collator; 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.Locale; import java.util.Map; import java.util.Scanner; import java.util.TreeMap;import org.apache.commons.collections.MapUtils;
public class demo{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("输出:"); String str = scan.nextLine();//以下是代码实现
System.out.println(str); String[] item =str.split(" "); Map<String,Integer> map= new HashMap<String, Integer>(); for(String s:item){ if(s.contains(",")){ String see=s.substring(0,s.length()-1); if(map.containsKey(see)){ map.put(see, map.get(see)+1); }else{ map.put(see, 1); } // System.out.println(see); }else if(s.contains(":")){ String see=s.substring(0,s.length()-1); if(map.containsKey(see)){ map.put(see, map.get(see)+1); }else{ map.put(see, 1); } // System.out.println(see); }else if(s.contains(".")){ String see=s.substring(0,s.length()-1); if(map.containsKey(see)){ map.put(see, map.get(see)+1); }else{ map.put(see, 1); } // System.out.println(see); }else{ if(map.containsKey(s)){ map.put(s.toLowerCase(), map.get(s)+1); }else{ map.put(s.toLowerCase(), 1); } //System.out.println(s); } } ValueComparator bvc = new ValueComparator(map); TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc); sorted_map.putAll(map); System.out.println("第一次:"+sorted_map); Iterator it = sorted_map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry =(Map.Entry) it.next(); Object key = entry.getKey(); Object value=entry.getValue(); System.out.println(key+" "+value); }}
}
class ValueComparator implements Comparator<String> {
Map<String, Integer> base; public ValueComparator(Map<String, Integer> map) { this.base = map; } public int compare(String a, String b) {if (base.get(a) > base.get(b)) {
return -1; }else if(base.get(a) < base.get(b)){ return 1; } else { if(a.charAt(0)<b.charAt(0)){ return -1; }else{ return 1; } } } }