下面列出了怎么用java.text.Collator的API类实例代码及写法,或者点击链接到github查看源代码。
private static int compareGraphObjects(GraphObject a, GraphObject b, Collection<String> sortFields,
Collator collator) {
for (String sortField : sortFields) {
String sa = (String) a.getProperty(sortField);
String sb = (String) b.getProperty(sortField);
if (sa != null && sb != null) {
int result = collator.compare(sa, sb);
if (result != 0) {
return result;
}
} else if (!(sa == null && sb == null)) {
return (sa == null) ? -1 : 1;
}
}
return 0;
}
private Collator getCollator() {
RuleBasedCollator base = (RuleBasedCollator)Collator.getInstance();
String rule = base.getRules();
try {
return new RuleBasedCollator(rule
+ "&B < \ud800\udc01 < \ud800\udc00"
+ ", \ud800\udc02, \ud800\udc03"
+ "; \ud800\udc04, \ud800\udc05"
+ "< \ud800\udc06 < \ud800\udc07"
+ "&FE < \ud800\udc08"
+ "&PE, \ud800\udc09"
+ "&Z < \ud800\udc0a < \ud800\udc0b < \ud800\udc0c"
+ "&\ud800\udc0a < x, X"
+ "&A < \ud800\udc04\ud800\udc05");
} catch (Exception e) {
errln("Failed to create new RulebasedCollator object");
return null;
}
}
private List<Analysis> getAnalysis(Entity[] entities, String tableName) {
List<Analysis> analysis = new ArrayList<Analysis>();
for (Entity entity : entities) {
Analysis a = (Analysis)entity;
if (tableName != null) {
if (a.getTableName().equals(tableName)) {
analysis.add(a);
}
} else {
analysis.add(a);
}
}
Collections.sort(analysis, new Comparator<Analysis>() {
public int compare(Analysis o1, Analysis o2) {
return Collator.getInstance().compare(o1.getName(), o2.getName());
}
});
return analysis;
}
public int compareTo(Object o) {
Snapshot s = (Snapshot)o;
// Alternative sorting: when sorting by snapshot type, the secondary
// sorting sorts custom-named snapshots alphabetically and default-named
// snapshots by timestamp, newest first. Custom-named snapshots display
// above the default-named snapshots.
if (alternativeSorting()) {
if (customName) {
if (!s.customName) return -1;
else return Collator.getInstance().compare(getDisplayName(), s.getDisplayName());
} else {
if (s.customName) return 1;
else return Long.compare(timestamp, s.timestamp);
}
} else {
return Collator.getInstance().compare(getDisplayName(), s.getDisplayName());
}
}
ListAdapter(Context context, List<String> listDataHeader,
HashMap<String, String> listChildData) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listDataChild = listChildData;
// HashMap will prevent duplicates
mapIndex = new LinkedHashMap<String, Integer>();
for (int i = listDataHeader.size() - 1; i >= 0; i--) {
mapIndex.put(listDataHeader.get(i).substring(0, 1).toUpperCase(Locale.getDefault()), i);
}
// create a list from the set to sort
final ArrayList<String> sectionList = new ArrayList<String>(mapIndex.keySet());
final Collator coll = Collator.getInstance(Locale.getDefault());
coll.setStrength(Collator.PRIMARY);
Collections.sort(sectionList, coll);
sections = new String[sectionList.size()];
sectionList.toArray(sections);
}
private ArrayList<String> getNames(String type) {
ArrayList<String> names = new ArrayList<String>();
if (type.equals(AuditRights.USER_TYPE)) {
User[] users = securityService.getUsers();
for (User user : users) {
if (!user.isAdmin()) {
names.add(user.getUsername());
}
}
} else {
Group[] groups = securityService.getGroups();
for (Group group : groups) {
names.add(group.getGroupname());
}
}
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Collator.getInstance().compare(s1, s2);
}
});
return names;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
Intent intent = getIntent();
_groups = new TreeSet<>(Collator.getInstance());
_groups.addAll(intent.getStringArrayListExtra("groups"));
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// set up the recycler view
_adapter = new GroupAdapter(this);
RecyclerView slotsView = findViewById(R.id.list_slots);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
slotsView.setLayoutManager(layoutManager);
slotsView.setAdapter(_adapter);
slotsView.setNestedScrollingEnabled(false);
for (String group : _groups) {
_adapter.addGroup(group);
}
}
/**
* You can set the heading country in headingCountryCode to show
* your favorite country as the head of the list
*
* @param context
* @param callbacks
* @param headingCountryCode
*/
public CountryPickerDialog(Context context, CountryPickerCallbacks callbacks,
@Nullable String headingCountryCode, boolean showDialingCode) {
super(context);
this.callbacks = callbacks;
this.headingCountryCode = headingCountryCode;
this.showDialingCode = showDialingCode;
countries = Utils.parseCountries(Utils.getCountriesJSON(this.getContext()));
Collections.sort(countries, new Comparator<Country>() {
@Override
public int compare(Country country1, Country country2) {
final Locale locale = getContext().getResources().getConfiguration().locale;
final Collator collator = Collator.getInstance(locale);
collator.setStrength(Collator.PRIMARY);
return collator.compare(
new Locale(locale.getLanguage(), country1.getIsoCode()).getDisplayCountry(),
new Locale(locale.getLanguage(), country2.getIsoCode()).getDisplayCountry());
}
});
}
private static int compareGraphObjects(GraphObject a, GraphObject b, Collection<String> sortFields,
Collator collator) {
for (String sortField : sortFields) {
String sa = (String) a.getProperty(sortField);
String sb = (String) b.getProperty(sortField);
if (sa != null && sb != null) {
int result = collator.compare(sa, sb);
if (result != 0) {
return result;
}
} else if (!(sa == null && sb == null)) {
return (sa == null) ? -1 : 1;
}
}
return 0;
}
/**
* Sorts the foreign keys alphabetically.
*
* @param caseSensitive Whether case matters
*/
public void sortForeignKeys(final boolean caseSensitive)
{
if (!_foreignKeys.isEmpty())
{
final Collator collator = Collator.getInstance();
Collections.sort(_foreignKeys, new Comparator() {
public int compare(Object obj1, Object obj2)
{
String fk1Name = ((ForeignKey)obj1).getName();
String fk2Name = ((ForeignKey)obj2).getName();
if (!caseSensitive)
{
fk1Name = (fk1Name != null ? fk1Name.toLowerCase() : null);
fk2Name = (fk2Name != null ? fk2Name.toLowerCase() : null);
}
return collator.compare(fk1Name, fk2Name);
}
});
}
}
@Override
protected void addNotify() {
super.addNotify();
List<FileObject> l = new ArrayList<FileObject>();
for (FileObject f : fo.getChildren()) {
if (f.isFolder() && group.contains(f) && VisibilityQuery.getDefault().isVisible(f)) {
l.add(f);
}
}
Collections.sort(l, new Comparator<FileObject>() { // #116545
Collator COLL = Collator.getInstance();
@Override
public int compare(FileObject f1, FileObject f2) {
return COLL.compare(f1.getNameExt(), f2.getNameExt());
}
});
setKeys(l);
}
public void TestDemoTest2() {
final Collator myCollation = Collator.getInstance(Locale.US);
final String defRules = ((RuleBasedCollator)myCollation).getRules();
String newRules = defRules + "& C < ch , cH, Ch, CH";
try {
RuleBasedCollator tblColl = new RuleBasedCollator(newRules);
for (int j = 0; j < TOTALTESTSET; j++) {
for (int n = j+1; n < TOTALTESTSET; n++) {
doTest(tblColl, testCases[Test2Results[j]],
testCases[Test2Results[n]], -1);
}
}
} catch (Exception foo) {
errln("Exception: " + foo.getMessage() +
"\nDemo Test 2 Table Collation object creation failed.\n");
}
}
public static HanziToPinyin getInstance() {
synchronized (HanziToPinyin.class) {
if (sInstance != null) {
return sInstance;
}
// Check if zh_CN collation data is available
final Locale locale[] = Collator.getAvailableLocales();
for (int i = 0; i < locale.length; i++) {
if (locale[i].equals(Locale.CHINA)) {
// Do self validation just once.
if (DEBUG) {
android.util.Log.d(TAG, "Self validation. Result: " +
doSelfValidation());
}
sInstance = new HanziToPinyin(true);
return sInstance;
}
}
android.util.Log.w(TAG,
"There is no Chinese collator, HanziToPinyin is disabled");
sInstance = new HanziToPinyin(false);
return sInstance;
}
}
@Override
protected AppListAdapter doInBackground(Void... params) {
List<IconPack> list = IconPackManager.getInstance().getAvailableIconPacks(IconPackActivity.this);
if(list.isEmpty())
return null;
else {
List<IconPack> finalList = new ArrayList<>();
IconPack dummyIconPack = new IconPack();
dummyIconPack.setPackageName(getPackageName());
dummyIconPack.setName(getString(R.string.tb_icon_pack_none));
Collections.sort(list, (ip1, ip2) -> Collator.getInstance().compare(ip1.getName(), ip2.getName()));
finalList.add(dummyIconPack);
finalList.addAll(list);
return new AppListAdapter(IconPackActivity.this, R.layout.tb_row, finalList);
}
}
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
Collections.addAll(listDataHeader, getResources().getStringArray(R.array.breeds_array));
final String[] fileNames = getResources().getStringArray(R.array.file_names);
// load file names
for (int i = 0; i < listDataHeader.size(); i++) {
listDataChild.put(listDataHeader.get(i), fileNames[i]);
}
if (null != recogs) {
listDataHeader = new ArrayList<>();
listDataHeader.addAll(recogs);
expListView.setFastScrollAlwaysVisible(false);
} else {
final Collator coll = Collator.getInstance(Locale.getDefault());
coll.setStrength(Collator.PRIMARY);
Collections.sort(listDataHeader, coll);
expListView.setFastScrollAlwaysVisible(true);
}
}
private Collator getCollator() {
RuleBasedCollator base = (RuleBasedCollator)Collator.getInstance();
String rule = base.getRules();
try {
return new RuleBasedCollator(rule
+ "&B < \ud800\udc01 < \ud800\udc00"
+ ", \ud800\udc02, \ud800\udc03"
+ "; \ud800\udc04, \ud800\udc05"
+ "< \ud800\udc06 < \ud800\udc07"
+ "&FE < \ud800\udc08"
+ "&PE, \ud800\udc09"
+ "&Z < \ud800\udc0a < \ud800\udc0b < \ud800\udc0c"
+ "&\ud800\udc0a < x, X"
+ "&A < \ud800\udc04\ud800\udc05");
} catch (Exception e) {
errln("Failed to create new RulebasedCollator object");
return null;
}
}
@SuppressFBWarnings(value = "DC_DOUBLECHECK", justification = "Before and after synchronization") //NON-NLS
public static Vector<TrackIcon> getAllTrackIcons() {
if (trackIcons == null) {
synchronized (TrackIcon.class) {
if (trackIcons == null) {
trackIcons = new Vector<>();
for (final String key : KEYS) {
trackIcons.add(new TrackIcon(key, RESOURCE_BUNDLE.getString(RESOURCE_BUNDLE_TRACKICON_PREFIX.concat(key))));
}
final Collator collator = Collator.getInstance();
trackIcons.sort((a, b) -> collator.compare(a.name, b.name));
trackIcons.add(0, new TrackIcon("", ""));
}
}
}
return trackIcons;
}
private Collation(String name, String language, String country,
int strength, int decomposition, boolean ucc) {
locale = new Locale(language, country);
collator = Collator.getInstance(locale);
if (strength >= 0) {
collator.setStrength(strength);
}
if (decomposition >= 0) {
collator.setDecomposition(decomposition);
}
strength = collator.getStrength();
isUnicodeSimple = false;
this.name = HsqlNameManager.newInfoSchemaObjectName(name, true,
SchemaObject.COLLATION);
charset = Charset.SQL_TEXT;
isUpperCaseCompare = ucc;
isFinal = true;
}
@Override
public List<String> getMatchingData(String searchText) {
if (StringUtils.isBlank(searchText) || !isValidPatternString(searchText)) {
return Collections.emptyList();
}
searchText = searchText.trim();
lastConstraint =
(StringColumnConstraint) currentConstraint.parseConstraintValue(searchText,
columnDataSource.getTableDataSource());
// Use a Collator to support languages other than English.
Collator collator = Collator.getInstance();
collator.setStrength(Collator.SECONDARY);
// @formatter:off
return dataSet.stream()
.filter(k -> lastConstraint.accepts(k, null))
.sorted( (k1, k2) -> collator.compare(k1, k2))
.collect(Collectors.toList());
// @formatter:on
}
/**
* 获取项目属性的文本字段
* @return ;
*/
public static ArrayList<String> getProjectFieldList() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
ArrayList<String> lstField = new ArrayList<String>();
int fieldCount = store
.getInt("net.heartsome.cat.ts.ui.preferencepage.ProjectPropertiesPreferencePage.fieldCount");
if (fieldCount > 0) {
for (int i = 0; i < fieldCount; i++) {
lstField.add(store
.getString("net.heartsome.cat.ts.ui.preferencepage.ProjectPropertiesPreferencePage.field" + i));
}
}
// 对中文按拼音排序
Collator collatorChinese = Collator.getInstance(java.util.Locale.CHINA);
Collections.sort(lstField, collatorChinese);
return lstField;
}
public static HanziToPinyin getInstance() {
synchronized (HanziToPinyin.class) {
if (sInstance != null) {
return sInstance;
}
// Check if zh_CN collation data is available
final Locale locale[] = Collator.getAvailableLocales();
for (int i = 0; i < locale.length; i++) {
if (locale[i].equals(Locale.CHINESE)) {
// Do self validation just once.
if (DEBUG) {
Log.d(TAG, "Self validation. Result: " + doSelfValidation());
}
sInstance = new HanziToPinyin(true);
return sInstance;
}
}
Log.w(TAG, "There is no Chinese collator, HanziToPinyin is disabled");
sInstance = new HanziToPinyin(false);
return sInstance;
}
}
/**
* Order projects by display name.
*/
public static Comparator<Project> projectDisplayNameComparator() {
return new Comparator<Project>() {
private final Collator LOC_COLLATOR = Collator.getInstance();
public int compare(Project o1, Project o2) {
ProjectInformation i1 = ProjectUtils.getInformation(o1);
ProjectInformation i2 = ProjectUtils.getInformation(o2);
int result = LOC_COLLATOR.compare(i1.getDisplayName(), i2.getDisplayName());
if (result != 0) {
return result;
} else {
result = i1.getName().compareTo(i2.getName());
if (result != 0) {
return result;
} else {
return System.identityHashCode(o1) - System.identityHashCode(o2);
}
}
}
};
}
public final void TestCollationKey( )
{
logln("testing CollationKey begins...");
Collator col = null;
try {
col = Collator.getInstance(Locale.ROOT);
} catch (Exception foo) {
errln("Error : " + foo.getMessage());
errln("Default collation creation failed.");
}
if (col == null) {
return;
}
String test1 = "Abcda", test2 = "abcda";
logln("Use tertiary comparison level testing ....");
CollationKey sortk1 = col.getCollationKey(test1);
CollationKey sortk2 = col.getCollationKey(test2);
doAssert(sortk1.compareTo(sortk2) > 0,
"Result should be \"Abcda\" >>> \"abcda\"");
CollationKey sortk3 = sortk2;
CollationKey sortkNew = sortk1;
doAssert(sortk1 != sortk2, "The sort keys should be different");
doAssert(sortk1.hashCode() != sortk2.hashCode(), "sort key hashCode() failed");
doAssert(sortk2.compareTo(sortk3) == 0, "The sort keys should be the same");
doAssert(sortk1 == sortkNew, "The sort keys assignment failed");
doAssert(sortk1.hashCode() == sortkNew.hashCode(), "sort key hashCode() failed");
doAssert(sortkNew != sortk3, "The sort keys should be different");
doAssert(sortk1.compareTo(sortk3) > 0, "Result should be \"Abcda\" >>> \"abcda\"");
doAssert(sortk2.compareTo(sortk3) == 0, "Result should be \"abcda\" == \"abcda\"");
long cnt1, cnt2;
byte byteArray1[] = sortk1.toByteArray();
byte byteArray2[] = sortk2.toByteArray();
doAssert(byteArray1 != null && byteArray2 != null, "CollationKey.toByteArray failed.");
logln("testing sortkey ends...");
}
public int compareTo(StringComparable o) {
final String pattern = o.toString();
if(m_text.equals(pattern)){//Code-point equals
return 0;
}
final int savedStrength = m_collator.getStrength();
int comp = 0;
// Is there difference more significant than case-order?
if(((savedStrength == Collator.PRIMARY) || (savedStrength == Collator.SECONDARY))){
comp = m_collator.compare(m_text, pattern );
}else{// more than SECONDARY
m_collator.setStrength(Collator.SECONDARY);
comp = m_collator.compare(m_text, pattern );
m_collator.setStrength(savedStrength);
}
if(comp != 0){//Difference more significant than case-order
return comp ;
}
// No difference more significant than case-order.
// Find case difference
comp = getCaseDiff(m_text, pattern);
if(comp != 0){
return comp;
}else{// No case differences. Less significant difference could exist
return m_collator.compare(m_text, pattern );
}
}
public void TestCollationKey()
{
String source = "-abcdefghijklmnopqrstuvwxyz#&^[email protected]";
Random r = new Random(3);
int s = checkValue(r.nextInt() % source.length());
int t = checkValue(r.nextInt() % source.length());
int slen = checkValue((r.nextInt() - source.length()) % source.length());
int tlen = checkValue((r.nextInt() - source.length()) % source.length());
String subs = source.substring((s > slen ? slen : s), (s >= slen ? s : slen));
String subt = source.substring((t > tlen ? tlen : t), (t >= tlen ? t : tlen));
myCollator.setStrength(Collator.TERTIARY);
CollationKey CollationKey1 = myCollator.getCollationKey(subs);
CollationKey CollationKey2 = myCollator.getCollationKey(subt);
int result = CollationKey1.compareTo(CollationKey2); // Tertiary
int revResult = CollationKey2.compareTo(CollationKey1); // Tertiary
report(("CollationKey(" + subs + ")"), ("CollationKey(" + subt + ")"), result, revResult);
myCollator.setStrength(Collator.SECONDARY);
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(subt);
result = CollationKey1.compareTo(CollationKey2); // Secondary
revResult = CollationKey2.compareTo(CollationKey1); // Secondary
report(("CollationKey(" + subs + ")") , ("CollationKey(" + subt + ")"), result, revResult);
myCollator.setStrength(Collator.PRIMARY);
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(subt);
result = CollationKey1.compareTo(CollationKey2); // Primary
revResult = CollationKey2.compareTo(CollationKey1); // Primary
report(("CollationKey(" + subs + ")"), ("CollationKey(" + subt + ")"), result, revResult);
String addOne = subs + "\uE000";
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(addOne);
result = CollationKey1.compareTo(CollationKey2);
if (result != -1)
errln("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed.");
result = CollationKey2.compareTo(CollationKey1);
if (result != 1)
errln("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed.");
}
public void TestCollationKey()
{
String source = "-abcdefghijklmnopqrstuvwxyz#&^[email protected]";
Random r = new Random(3);
int s = checkValue(r.nextInt() % source.length());
int t = checkValue(r.nextInt() % source.length());
int slen = checkValue((r.nextInt() - source.length()) % source.length());
int tlen = checkValue((r.nextInt() - source.length()) % source.length());
String subs = source.substring((s > slen ? slen : s), (s >= slen ? s : slen));
String subt = source.substring((t > tlen ? tlen : t), (t >= tlen ? t : tlen));
myCollator.setStrength(Collator.TERTIARY);
CollationKey CollationKey1 = myCollator.getCollationKey(subs);
CollationKey CollationKey2 = myCollator.getCollationKey(subt);
int result = CollationKey1.compareTo(CollationKey2); // Tertiary
int revResult = CollationKey2.compareTo(CollationKey1); // Tertiary
report(("CollationKey(" + subs + ")"), ("CollationKey(" + subt + ")"), result, revResult);
myCollator.setStrength(Collator.SECONDARY);
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(subt);
result = CollationKey1.compareTo(CollationKey2); // Secondary
revResult = CollationKey2.compareTo(CollationKey1); // Secondary
report(("CollationKey(" + subs + ")") , ("CollationKey(" + subt + ")"), result, revResult);
myCollator.setStrength(Collator.PRIMARY);
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(subt);
result = CollationKey1.compareTo(CollationKey2); // Primary
revResult = CollationKey2.compareTo(CollationKey1); // Primary
report(("CollationKey(" + subs + ")"), ("CollationKey(" + subt + ")"), result, revResult);
String addOne = subs + "\uE000";
CollationKey1 = myCollator.getCollationKey(subs);
CollationKey2 = myCollator.getCollationKey(addOne);
result = CollationKey1.compareTo(CollationKey2);
if (result != -1)
errln("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed.");
result = CollationKey2.compareTo(CollationKey1);
if (result != 1)
errln("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed.");
}
private static final int getMask(final int strength) {
switch (strength) {
case Collator.PRIMARY:
return 0xFFFF0000;
case Collator.SECONDARY:
return 0xFFFFFF00;
default:
return 0xFFFFFFFF;
}
}
@Override
public int compare(Object o1, Object o2)
{
String key1 = getSortKey(o1);
String key2 = getSortKey(o2);
final Collator collator = Collator.getInstance();
if (!key1.equals(key2))
{
return collator.compare(key1, key2);
}
return collator.compare(String.valueOf(o1), String.valueOf(o2));
}
/**
* Constructor
*/
DocLocale(DocEnv docenv, String localeName, boolean useBreakIterator) {
this.docenv = docenv;
this.localeName = localeName;
this.useBreakIterator = useBreakIterator;
locale = getLocale();
if (locale == null) {
docenv.exit();
} else {
Locale.setDefault(locale); // NOTE: updating global state
}
collator = Collator.getInstance(locale);
sentenceBreaker = BreakIterator.getSentenceInstance(locale);
}
@Override
protected Comparator getItemsComparator() {
return (v1, v2) -> {
Collator collator = Collator.getInstance();
int comparability = collator.compare(v1, v2);
return comparability;
};
}