zoukankan      html  css  js  c++  java
  • 金山网络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值进行排序

     

  • 相关阅读:
    Python class:定义类
    Python return函数返回值详解
    Python None(空值)及用法
    Python函数值传递和引用传递(包括形式参数和实际参数的区别)
    Python函数的定义
    Python函数(函数定义、函数调用)用法详解
    Python reversed函数及用法
    Python zip函数及用法
    Python break用法详解
    Python嵌套循环实现冒泡排序
  • 原文地址:https://www.cnblogs.com/wuxinliulei/p/4168230.html
Copyright © 2011-2022 走看看