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值进行排序

     

  • 相关阅读:
    Effective C++ 笔记 —— Item 6: Explicitly disallow the use of compiler-generated functions you do not want.
    Oracle DataBase 用户管理与权限管理
    企业邮箱配置SSL发送邮件
    如何知道安装程序在进行安装时对你的电脑到底做了什么?
    架构师笔记:康威定律
    conda 源配置
    myBatis的批量提交方式
    转载:request_time和upstream_response_time详解
    [PowerShell]比较运算符
    [PowerShell]字符串
  • 原文地址:https://www.cnblogs.com/wuxinliulei/p/4168230.html
Copyright © 2011-2022 走看看