爱程序网

Java实现中文字符串的排序功能

来源: 阅读:

 1 package test;
 2 
 3 /**
 4  * 
 5  * @Title          书的信息类
 6  * @author         LR
 7  * @version     1.0
 8  * @since         2016-04-21
 9  */
10 
11 public class Book {
12 
13     private String book_id;
14     
15     private String book_name;
16     
17     private String publishing_house;
18     
19     public Book(String book_id, String book_name, String publishing_house) {
20         super();
21         this.book_id = book_id;
22         this.book_name = book_name;
23         this.publishing_house = publishing_house;
24     }
25 
26     public String getBook_id() {
27         return book_id;
28     }
29 
30     public void setBook_id(String book_id) {
31         this.book_id = book_id;
32     }
33 
34     public String getBook_name() {
35         return book_name;
36     }
37 
38     public void setBook_name(String book_name) {
39         this.book_name = book_name;
40     }
41 
42     public String getPublishing_house() {
43         return publishing_house;
44     }
45 
46     public void setPublishing_house(String publishing_house) {
47         this.publishing_house = publishing_house;
48     }
49 
50     @Override
51     public String toString() {
52         // TODO Auto-generated method stub
53         return "书号"+book_id+"\n书名"+book_name+"\n出版社"+publishing_house;
54     }
55 }
 1 package test;
 2 
 3 import java.text.Collator;
 4 
 5 /**
 6  * 
 7  * @Title          中文字符串排序功能
 8  * @author         LR
 9  * @version     1.0
10  * @since         2016-04-21
11  */
12 
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.Comparator;
16 
17 public class CollectionChineseSort implements Comparator<Book>{
18     
19     Collator collator= Collator.getInstance(java.util.Locale.CHINA);
20     
21     public static void main(String[] args) {
22         
23         ArrayList<Book> list=new ArrayList<Book>();
24         
25         list.add(new Book("1","英语","英语出版社"));
26         list.add(new Book("2","日语","日语出版社"));
27         list.add(new Book("3","德语","德语出版社"));
28         list.add(new Book("4","法语","法语出版社"));
29         list.add(new Book("5","俄语","俄语出版社"));
30         
31         Collections.sort(list,new CollectionChineseSort());
32         
33         for (Book book:list){  
34             System.out.println(book);  
35         }  
36     }
37 
38     @Override
39     public int compare(Book book1, Book book2) {
40         // TODO Auto-generated method stub
41         
42         int compare_value=collator.compare(book1.getBook_name(),book2.getBook_name());
43         
44         if(compare_value>0){
45             return 1;
46         }
47         if(compare_value<0){
48             return -1;
49         }
50         
51         return 0;
52     }
53 }

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助