我们可以使用java.text.Collator该类以特定于语言的顺序对字符串进行排序。使用java.text.Collator该类可使字符串不仅按其字符的ASCII码排序,而且将遵循字符的语言自然顺序。
如果预定义的排序规则不符合您的需求,则可以设计自己的规则并将其分配给RuleBasedCollator对象。自定义的排序规则包含在String传递给RuleBasedCollator构造函数的对象中。
package org.nhooo.example.text; import java.text.ParseException; import java.text.RuleBasedCollator; import java.util.Arrays; import java.util.Collections; public class RuleBasedCollatorDemo { public static void main(String[] args) { String rule1 = ("< a < b < c"); String rule2 = ("< c < b < a"); String rule3 = ("< c < a < b"); String words[] = {"apple", "banana", "carrot", "apricot", "blueberry", "cabbage"}; try { RuleBasedCollator rb1 = new RuleBasedCollator(rule1); RuleBasedCollator rb2 = new RuleBasedCollator(rule2); RuleBasedCollator rb3 = new RuleBasedCollator(rule3); System.out.println("original: "); System.out.println(Arrays.toString(words)); // 根据Rule1排序 Collections.sort(Arrays.asList(words), rb1); System.out.println("rule: " + rb1.getRules()); System.out.println(Arrays.toString(words)); // 根据Rule2排序 Collections.sort(Arrays.asList(words), rb2); System.out.println("rule: " + rb2.getRules()); System.out.println(Arrays.toString(words)); // 根据Rule3排序 Collections.sort(Arrays.asList(words), rb3); System.out.println("rule: " + rb3.getRules()); System.out.println(Arrays.toString(words)); } catch (ParseException e) { e.printStackTrace(); } } }
下面是使用不同 RuleBasedCollator 对字符串进行排序的结果
original: [apple, banana, carrot, apricot, blueberry, cabbage] rule: < a < b < c [apple, apricot, banana, blueberry, cabbage, carrot] rule: < c < b < a [cabbage, carrot, banana, blueberry, apple, apricot] rule: < c < a < b [cabbage, carrot, apple, apricot, banana, blueberry]