Java -------- 首字母相关排序总结
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+“--”); }
输出: 北京--成都--广州--邯郸--上海--深圳--天津--武汉--西安--郑州--
已上是自己总结的字母排序的案例,希望对各位有所帮助。