How do I sort the list by pinyin letters?

Source: Internet
Author: User

1. First, create a list <string>

List <string> strlist = new arraylist <string> (); <br/> strlist. add ("I am codenong"); <br/> strlist. add ("Table Security Market"); <br/> strlist. add ("abcdef"); <br/> strlist. add ("= DSF China"); <br/> strlist. add ("? /DSF China "); <br/> strlist. Add (" hiapk "); <br/> strlist. Add (" himarket ");

2. Create another char-to-int method.

Static int getgbcode (char c) {<br/> byte [] bytes = NULL; <br/> try {<br/> bytes = new stringbuffer (). append (c ). tostring (). getbytes ("GBK"); <br/>} catch (unsupportedencodingexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> If (bytes. length = 1) {<br/> return bytes [0]; <br/>}< br/> int A = bytes [0]-0xa0 + 256; <br/> int B = bytes [1]-0xa0 + 256; </P> <p> return a * 100 + B; <br/>}

Getbytes ("GBK ")

Note: this is sorted by "GBK". Do not use UTF-8 by default. The sorting is not accurate.

3. Create a comparator and compare it:

Collections. sort (strlist, new comparator <string> () {<br/> Public int compare (string O1, string O2) {<br/> char [] a1 = o1.tochararray (); <br/> char [] a2 = o2.tochararray (); </P> <p> for (INT I = 0; I <a1.length & I <a2.length; I ++) {<br/> int C1 = getgbcode (A1 [I]); <br/> int C2 = getgbcode (A2 [I]); </P> <p> system. out. println (New stringbuffer (). append (C1 ). tostring (); <br/> system. out. println (New stringbuffer (). append (C2 ). tostring (); </P> <p> If (C1 = c2) <br/> continue; </P> <p> return c1-c2; <br/>}</P> <p> If (a1.length = a2.length) {<br/> return 0; <br/>}</P> <p> return a1.length-a2.length; <br/>}< br/> });

4. Print it out

For (string STR: strlist) {<br/> system. Out. println (STR); <br/>}

The output is as follows:

= DSF China
? /DSF China
Server market
I'm coannon.


End: This allows for simple sorting. It is also sorted by pinyin letters according to GBK encoding. UTF-8 encoding does not work. For more powerful functions, we need to look for components of Pinyin sorting.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.