干货分享,排序自己收集的单词,并且计算是否重复
还在苦于自己收集的常用词汇不能够正确排序而烦恼吗,还在苦于单词记重复了而烦恼吗,还在苦于找不到合适的工具来排序吗
只要一个赞,您就可以把代码捧回家,让你的单词清晰可见,安然有序,享受自己创造的过程。
下面是源码,万恶之源
1 package com.hp.word; 2 3 import java.io.*; 4 import java.util.TreeMap; 5 import java.util.Map; 6 7 /** 8 * 排序单词 9 * 10 * @author Administrator 11 *资料: http://wenda.so.com/u/1901333518 12 */ 13 public class Sort2 { 14 // 定义一个Treemap集合 15 16 private static TreeMap<String, Integer> words = new TreeMap<String, Integer>( 17 String.CASE_INSENSITIVE_ORDER); 18 19 // String.CASE_INSENSITIVE_ORDER 忽略大小写 20 /** 21 * 单词排序并且计算重复 22 * 23 * @throws IOException 24 */ 25 private static void sort() throws IOException { 26 27 File f = new File("e:\\word.txt"); 28 // 装饰模式 29 BufferedReader reader = new BufferedReader(new InputStreamReader( 30 new FileInputStream(f))); 31 // 单词 32 String word = null; 33 // 如果读取的这一行不为空的话 34 while ((word = reader.readLine()) != null) { 35 //判断是否存在键所对应的值,即判断是否有重复单词 36 if (words.containsKey(word)) 37 words.put(word, words.get(word) + 1); 38 else 39 words.put(word, 1); 40 } 41 reader.close(); 42 //排序后写入 43 outFile(f); 44 } 45 /** 46 * 重新写入文件,并且计算值 47 * @param f 48 * @throws FileNotFoundException 49 * @throws IOException 50 */ 51 private static void outFile(File f) throws FileNotFoundException, 52 IOException { 53 54 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( 55 new FileOutputStream(f))); 56 57 for (Map.Entry<String, Integer> item : words.entrySet()) { 58 59 writer.write(item.getKey() + "\t" + judge(item.getValue())); 60 writer.newLine(); 61 } 62 writer.close(); 63 } 64 /** 65 * 判断次数是否大于2 66 * @param number 67 * @return 68 */ 69 public static String judge(Integer number) { 70 int n = number; 71 if (n < 2) { 72 return " "; 73 } else { 74 return number + ""; 75 } 76 77 } 78 79 public static void main(String args[]) throws IOException { 80 sort(); 81 System.out.println("成功"); 82 } 83 }