Java -------- 首字母相關排序總結
阿新 • • 發佈:2018-12-11
Java 字串陣列首字母排序
字串陣列按首字母排序:(區分大小寫)
String[] strings = new String[]{"ba","aa","CC","Ba","DD","ee","dd"};
Arrays.sort(strings);
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i]+"----");
}
輸出:Ba----CC----DD----aa----ba----dd----ee----
List<String>排序
List<String> list = new ArrayList<>(); list.add("Bli"); list.add("Aa"); list.add("Ccn"); list.add("Bal"); list.add("dm"); list.add("Dn"); list.add("lm"); list.add("cm"); list.add("aaa"); Collections.sort(list); System.out.print(list+"\n");
輸出:[Aa, Bal, Bli, Ccn, Dn, aaa, cm, dm, lm]
Java 字串陣列首字母排序(不區分大小寫)
//不區分大小寫比較 String source[] = { "dad", "bood", "bada", "Admin", "Aa ", "A ", "Good", "aete", "cc", "Ko", "Beta", "Could" }; List<String> list = Arrays.asList(source); //String.CASE_INSENSITIVE_ORDER A在 a 前面 Collections.sort(list, String.CASE_INSENSITIVE_ORDER); System.out.println(list);
輸出:[A , Aa , Admin, aete, bada, Beta, bood, cc, Could, dad, Good, Ko]
中文首字母排序
List<String> data = new ArrayList<String>(); data.add("上海"); data.add("天津"); data.add("北京"); data.add("深圳"); data.add("廣州"); data.add("成都"); data.add("西安"); data.add("武漢"); data.add("鄭州"); data.add("邯鄲"); Collections.sort(data, new Comparator<String>() { Collator collator = Collator.getInstance(Locale.CHINA); @Override public int compare(String o1, String o2) { CollationKey key1 = collator.getCollationKey(o1); CollationKey key2 = collator.getCollationKey(o2); return key1.compareTo(key2); } }); for (String str : data) { System.out.print(str+“--”); }
輸出: 北京--成都--廣州--邯鄲--上海--深圳--天津--武漢--西安--鄭州--
已上是自己總結的字母排序的案例,希望對各位有所幫助。