Java编程中怎样实现中文排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java编程中怎样实现中文排序相关的知识,希望对你有一定的参考价值。
简单的实现排序,可以参考如下的代码
import java.text.Collator;import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
public class PYDemo
public static void main(String[] args)
String[] names= "赵z子z龙l","刘l备b","关g羽y","张z飞f";
System.out.println("排序前"+Arrays.toString(names));
Comparator cpt = Collator.getInstance(Locale.CHINA);
Arrays.sort(names, cpt);
System.out.println("排序后"+Arrays.toString(names));
测试输出
排序前[赵z子z龙l, 刘l备b, 关g羽y, 张z飞f]排序后[关g羽y, 刘l备b, 张z飞f, 赵z子z龙l]
如果有一些非常用的汉字,生僻字等,建议使用一些jar包实现,比如pinyin4j
参考技术A 第一种情况:Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
String[] arr = “张三”, “李四”, “王五”, “刘六” ;
Arrays.sort(arr, cmp);
for (int i = 0; i 《 arr.length; i++)
System.out.println(arr[i]);
第二种情况:
//ComparableBean.java
import java.text.CollationKey;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.Comparator;
public class ComparableBean
private String name;
public ComparableBean(String name)
this.name = name;
public String getName()
return name;
public void setName(String name)
this.name = name;
class ComparableBeanComparator implements Comparator//
RuleBasedCollator collator; // you can set your rules for the instance “collator”
public ComparableBeanComparator()
collator = (RuleBasedCollator)Collator.getInstance(java.util.Locale.CHINA);// try testing various locales
Java实现数组的中文排序
1 package demo; 2 3 import java.text.Collator; 4 import java.util.ArrayList; 5 import java.util.Arrays; 6 import java.util.Comparator; 7 8 public class Demo { 9 10 @SuppressWarnings("unchecked") 11 public static void main(String[] args) { 12 13 sort(); 14 } 15 16 //按照中文第一个字母升序排列的排序 17 public static void sort(){ 18 Comparator<Object> com=Collator.getInstance(java.util.Locale.CHINA); 19 String[] newArray={"中山","汕头","广州","安庆","阳江","南京","武汉","北京","安阳","北方"}; 20 Arrays.sort(newArray,com); 21 for(String i:newArray){ 22 System.out.print(i+" "); 23 } 24 } 25 26 }
以上是关于Java编程中怎样实现中文排序的主要内容,如果未能解决你的问题,请参考以下文章