开发者社区> 问答> 正文

java程序中如何添加按照字母顺序排序

public class Main2 {
public static void main(String[] args) {
int count = 0;
File file = new File("F:\1.txt");
String s = "";
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
        try {
            while ((s = br.readLine()) != null) {
                buffer.append(s + '\n');
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Pattern p = Pattern.compile("\\b[a-zA-Z]+\\b");
    Matcher m = p.matcher(buffer.toString());
    while(m.find()) {
        System.out.println(m.group());
        count ++ ;
    }
    System.out.println("总共:" + count + "个单词");
}
}

展开
收起
蛮大人123 2016-03-24 16:15:56 2536 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    Comparator<String> comparator = new Comparator<String>(){  
       public int compare(String s1, String s2) {
         return s1.compareTo(s2);
         }
    };
    Matcher m = p.matcher(buffer.toString());
    ArrayList<String> list = new ArrayList<String>();
    while(m.find()) {
            list.add(m.group().toString());
            count ++ ;
        }
    Collections.sort(list,comparator); 
    for(String s: list)  
       System.out.println(s);  
     } 
     System.out.println("总共:" + count + "个单词");
    2019-07-17 19:13:00
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载