package demo61; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.commons.io.FileUtils; /** * 對字符串進行統計並做排序 * @author mengfeiyang * */ public class KeywordCount { public static void main(String[] args) throws IOException { List<String> ll = FileUtils.readLines(new File("test.txt"), "UTF-8"); TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>(); for(String l : ll){ String keyword = l.split(" ")[0]; if(treeMap.containsKey(keyword)){ int index = treeMap.get(keyword); index++; treeMap.put(keyword, index); }else{ treeMap.put(keyword, 1); } } for(Entry<String, Integer> e : treeMap.entrySet()){ System.out.println(e.getKey()+" --> "+e.getValue()); } System.out.println("----排序後----"); //--作排序 List<Entry<String,Integer>> sortMap = new ArrayList<Entry<String,Integer>>(treeMap.entrySet()); Collections.sort(sortMap, new Comparator<Entry<String,Integer>>(){ @Override public int compare(Entry<String, Integer> o1,Entry<String, Integer> o2) { //return o1.getValue() - o2.getValue(); //默認從小到大排序方式 return -(o1.getValue() - o2.getValue()); //從大到小排序方式 } }); for (int i = 0; i < sortMap.size(); i++) { Entry<String,Integer> ent=sortMap.get(i); System.out.println(ent.getKey()+" --> "+ent.getValue()); } } }
執行結果: 12345 --> 2 347834 --> 3 347835 --> 1 ----排序後---- 347834 --> 3 12345 --> 2 347835 --> 1
test.txt 中的內容: 12345 adfdf 347834 fkdfjkdjf 12345 adfdf 347834 adfdf2 347834 中文 347835 中文