金山网络2014春季Android实习生招聘-成都站-笔试第二题

一个文件名为input.txt的文件当中,每一行都有一个单词,要求统计单词出现的频率,并且按照从小到大出现次数打印,次数相同的按照首字母顺序排序。

 

package jinshanwangluo.exam;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 
 * @author guoxm
 * @date 2014-12-16
 */
public class SortWords {
      public static void main(String args[]){
    	  try{
    		  new SortWords().sortWordInFile();  
    	  }catch(IOException ex){
    		  System.out.println("未找到相关文件");
    		  ex.printStackTrace();
    	  }
    	  
      }
    
     
    @SuppressWarnings("unchecked")
	public void sortWordInFile() throws IOException{
    	  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/jinshanwangluo/exam/input.txt")));
          //因为有单词出现次数相同的情况,因此不能用出现次数作为key
    	  Map<String,Integer> hashmap = new HashMap<String,Integer>();
    	  String word = null;
          while((word = br.readLine())!= null){
        	  if(hashmap.containsKey(word)){
        		  hashmap.put(word,hashmap.get(word)+1);
        	  }else{
        		  hashmap.put(word,1);
        	  }
          }
          List arrayList = new ArrayList(hashmap.entrySet());
          Collections.sort(arrayList,new Comparator<Map.Entry>(){  
              public int compare(Map.Entry entry1, Map.Entry entry2) {
            	  if(entry1.getValue() != entry2.getValue()){
            		  return (Integer)entry1.getValue() - (Integer)entry2.getValue();
            	  }else{
            		  return ((String)entry1.getKey()).compareTo((String)entry2.getKey());
            	  }
              }  
          	});

        System.out.println(arrayList);
        //此时ArrayList当中是Object对象
        for(Object object : arrayList){
    	    Map.Entry entry = (Map.Entry)object;
    	    System.out.println(entry.getKey()+" " +entry.getValue());
        }
      }
}

 

主要难点在于针对HashMap的value值进行排序

 

 

posted @ 2014-12-16 22:21  无心流泪  阅读(215)  评论(0编辑  收藏  举报