对map里的数据进行排序

    long t1 = System.currentTimeMillis();
    String s;
    String fileName1 = "G:/caseDetail.txt";
    String fileName2 = "G:/result.txt";
    try {
      BufferedReader br = new BufferedReader(new FileReader(fileName1));
      BufferedWriter bw = new BufferedWriter(new FileWriter(fileName2));
      StringBuffer sb = new StringBuffer();
      // 将文件内容存入StringBuffer中
      while ((s = br.readLine()) != null) {
        sb.append(s);
      }
      String str = sb.toString();
      Vector vString = AemanticAnalysisUtil.participle(str, true);
      // 分隔字符串并存入数组
      int count = 0;
      Map myTreeMap = new TreeMap();
      // 遍历数组将其存入Map中
      for (int i = 0; i < vString.size(); i++) {
        if(vString.get(i).length()==1||vString.get(i).equals("案件")||vString.get(i).equals("详情")){
          continue;
        }
        if (myTreeMap.containsKey(vString.get(i))) {
          count = myTreeMap.get(vString.get(i));
          myTreeMap.put(vString.get(i), count + 1);
        } else {
          myTreeMap.put(vString.get(i), 1);
        }
      }
      System.out.println("单词统计的结果请见当前目录result.txt文件");
      // 将map.entrySet()转换成list
      List> list = new ArrayList>(myTreeMap.entrySet());
      // 通过比较器实现排序
      Collections.sort(list, new Comparator>() {
        // 降序排序
        public int compare(Entry o1, Entry o2) {
          return o2.getValue().compareTo(o1.getValue());
        }
      });
      int num = 1;
      // 将结果写入文件
      for (Map.Entry map : list) {
        if (map.getValue()>100) {
          bw.write("出现次数第" + num + "的单词为:" + map.getKey() + ",出现频率为" + map.getValue() + "次");
          bw.newLine();
          System.out.println(map.getKey() + ":" + map.getValue());
          num++;
        }
      }
      bw.write("耗时:" + (System.currentTimeMillis() - t1) + "ms");
      br.close();
      bw.close();
      System.out.println("耗时:" + (System.currentTimeMillis() - t1) + "ms");
    } catch (Exception e) {
      e.printStackTrace();
    }
  

你可能感兴趣的:(java基础)