Java Code Examples for java.text.Collator

The following are top voted examples for showing how to use java.text.Collator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hibernate-ogm-redis   File: AbstractRedisDialect.java   Source Code and License 6 votes vote down vote up
/**
 * Construct a key based on the key columns:
 * Single key: Use the value as key
 * Multiple keys: Serialize the key using a JSON map.
 */
private String keyToString(String[] columnNames, Object[] columnValues) {
	if ( columnNames.length == 1 ) {
		return columnValues[0].toString();
	}

	Collator collator = Collator.getInstance( Locale.ENGLISH );
	collator.setStrength( Collator.SECONDARY );

	Map<String, Object> idObject = new TreeMap<>( collator );

	for ( int i = 0; i < columnNames.length; i++ ) {
		idObject.put( columnNames[i], columnValues[i] );
	}

	return strategy.serialize( idObject );
}
 
Example 2
Project: incubator-netbeans   File: AntScriptUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Finds the names of callable targets in an Ant script.
 * @param script Ant script to inspect
 * @return list of target names, sorted (by locale)
 * @throws IOException if the script cannot be inspected
 */
public static List<String> getCallableTargetNames(FileObject script) throws IOException {
    AntProjectCookie apc = antProjectCookieFor(script);
    Set<TargetLister.Target> allTargets = TargetLister.getTargets(apc);
    SortedSet<String> targetNames = new TreeSet<String>(Collator.getInstance());
    for (TargetLister.Target target : allTargets) {
        if (target.isOverridden()) {
            // Cannot call it directly.
            continue;
        }
        if (target.isInternal()) {
            // Should not be called from outside.
            continue;
        }
        targetNames.add(target.getName());
    }
    return new ArrayList<String>(targetNames);
}
 
Example 3
Project: incubator-netbeans   File: ModuleDependencyTest.java   Source Code and License 6 votes vote down vote up
public void testLocalizedNameComparator() throws Exception {
        NbModuleProject module = generateStandaloneModule("module");
        ModuleList ml = module.getModuleList();
        ModuleDependency[] deps = new ModuleDependency[] {
            new ModuleDependency(ml.getEntry("org.apache.tools.ant.module")),
            new ModuleDependency(ml.getEntry("org.openide.loaders")),
            new ModuleDependency(ml.getEntry("org.apache.tools.ant.module")),
            new ModuleDependency(ml.getEntry("org.openide.io")),
            new ModuleDependency(ml.getEntry("org.jdesktop.layout")),
            new ModuleDependency(ml.getEntry("org.openide.filesystems")),
            new ModuleDependency(ml.getEntry("org.openide.execution")),
        };
        
        for (int i = 0; i < deps.length; i++) {
            for (int j = 0; j < deps.length; j++) {
                int locNameResult = Collator.getInstance().compare(
                        deps[i].getModuleEntry().getLocalizedName(),
                        deps[j].getModuleEntry().getLocalizedName());
                int realResult = ModuleDependency.LOCALIZED_NAME_COMPARATOR.compare(deps[i], deps[j]);
                assertTrue("ordering works: " + deps[i] + " <--> " + deps[j],
                        locNameResult > 0 ? realResult > 0 :
                            (locNameResult == 0 ? realResult == 0 : realResult < 0));
//                (int) Math.signum(locNameResult), (int) Math.signum(realResult));
            }
        }
    }
 
Example 4
Project: incubator-netbeans   File: Util.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
                }
            }
        }
    };
}
 
Example 5
Project: incubator-netbeans   File: BrowseFolders.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 6
Project: incubator-netbeans   File: ClasspathPanel.java   Source Code and License 6 votes vote down vote up
private void refreshJavaPlatforms() {
    SortedSet<JavaPlatform> platforms = new TreeSet<JavaPlatform>(new Comparator<JavaPlatform>() {
        Collator COLL = Collator.getInstance();
        public int compare(JavaPlatform p1, JavaPlatform p2) {
            int res = COLL.compare(p1.getDisplayName(), p2.getDisplayName());
            if (res != 0) {
                return res;
            } else {
                return System.identityHashCode(p1) - System.identityHashCode(p2);
            }
        }
    });
    platforms.addAll(Arrays.asList(JavaPlatformManager.getDefault().getInstalledPlatforms()));
    javaPlatform.setModel(new DefaultComboBoxModel(platforms.toArray(new JavaPlatform[platforms.size()])));
    JavaPlatform pf = jdkConf.getSelectedPlatform();
    if (pf == null) {
        pf = JavaPlatformManager.getDefault().getDefaultPlatform();
    }
    javaPlatform.setSelectedItem(pf);
}
 
Example 7
Project: dev-courses   File: Collation.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 8
Project: incubator-netbeans   File: DBElement.java   Source Code and License 6 votes vote down vote up
/** Compares two elements.
 * @param obj the reference object with which to compare.
 * @return the value 0 if the argument object is equal to
 * this object; -1 if this object is less than the object
 * argument; and 1 if this object is greater than the object argument.
 * Null objects are "smaller".
 */
public int compareTo(Object obj) {
    // null is not allowed
    if (obj == null)
        throw new ClassCastException();
    if (obj == this)
        return 0;

    String thisName = getName().getFullName();
    String otherName = ((DBElement) obj).getName().getFullName();
    
    if (thisName == null)
        return (otherName == null) ? 0 : -1;
        
    if (otherName == null)
        return 1;
        
    int ret = Collator.getInstance().compare(thisName, otherName);
    // if both names are equal, both objects might have different types.
    // If so order both objects by their type names 
    // (necessary to be consistent with equals)
    if ((ret == 0) && (getClass() != obj.getClass()))
        ret = getClass().getName().compareTo(obj.getClass().getName());
    
    return ret;
}
 
Example 9
Project: java-course   File: SortLinesAscendingAction.java   Source Code and License 6 votes vote down vote up
/**
 * Sorts lines in given text ascending.
 * 
 * @param text
 *            Input text.
 * @return Text with sorted lines.
 */
private String sortLinesAsc(String text) {
    String[] lines = text.split("\\n");

    Arrays.sort(lines, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String language = LocalizationProvider.getInstance()
                    .getLanguage();
            Locale locale = new Locale(language);
            Collator collator = Collator.getInstance(locale);
            int r = collator.compare(o1, o2);
            return r;
        }
    });

    StringBuilder builder = new StringBuilder(text.length());
    for (int i = 0; i < lines.length; ++i) {
        builder.append(lines[i]);
        builder.append("\n");
    }

    return builder.toString();
}
 
Example 10
Project: OpenDiabetes   File: Collation.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 11
Project: openjdk-jdk10   File: G7Test.java   Source Code and License 6 votes vote down vote up
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");
    }
}
 
Example 12
Project: alfresco-repository   File: GetAuthoritiesCannedQuery.java   Source Code and License 6 votes vote down vote up
public AuthComparator(String fieldName, SortOrder sortOrder)
{
    if (DISPLAY_NAME.equals(fieldName))
    {
        sortByDisplayName = true;
        sortByShortName = false;
    }
    else if (SHORT_NAME.equals(fieldName))
    {
        sortByDisplayName = false;
        sortByShortName = true;
    }
    else if (AUTHORITY_NAME.equals(fieldName))
    {
        sortByDisplayName = false;
        sortByShortName = false;
    }
    else
    {
        throw new IllegalArgumentException("Authorities should be sorted by "+DISPLAY_NAME+", "+AUTHORITY_NAME+" or "+SHORT_NAME+". Asked use "+fieldName);
    }
        
    this.sortOrder = sortOrder;
    this.collator = Collator.getInstance(); // note: currently default locale
}
 
Example 13
Project: KUtils-master   File: HanziToPinyin.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 14
Project: java-course   File: SortLinesDescendingAction.java   Source Code and License 6 votes vote down vote up
/**
 * Sorts lines in given text descending.
 * 
 * @param text
 *            Input text.
 * @return Text with sorted lines.
 */
private String sortLinesDesc(String text) {
    String[] lines = text.split("\\n");

    Arrays.sort(lines, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String language = LocalizationProvider.getInstance()
                    .getLanguage();
            Locale locale = new Locale(language);
            Collator collator = Collator.getInstance(locale);
            int r = collator.compare(o2, o1);
            return r;
        }
    });

    StringBuilder builder = new StringBuilder(text.length());
    for (int i = 0; i < lines.length; ++i) {
        builder.append(lines[i]);
        builder.append("\n");
    }

    return builder.toString();

}
 
Example 15
Project: ArcaneMagic   File: CategoryRegistry.java   Source Code and License 6 votes vote down vote up
public static void sortCategories()
{
	List<NotebookCategory> ours = NotebookCategory.REGISTRY.getValues().stream()
			.filter((c) -> c.getRegistryName().getResourceDomain().equals(ArcaneMagic.MODID))
			.collect(Collectors.toList());
	List<ResourceLocation> theirNames = new ArrayList<>();
	NotebookCategory.REGISTRY.getValues().stream()
			.filter((c) -> !c.getRegistryName().getResourceDomain().equals(ArcaneMagic.MODID))
			.sorted(Collator.getInstance()).forEach((c) -> theirNames.add(c.getRegistryName()));
	theirNames.sort(Collator.getInstance());
	ImmutableList.Builder<NotebookCategory> bob = ImmutableList.builder();
	bob.addAll(ours);
	for (ResourceLocation loc : theirNames)
		bob.add(NotebookCategory.REGISTRY.getValue(loc));
	ArcaneMagicAPI.setCategoryList(bob.build());
	freeze();
}
 
Example 16
Project: chat-sdk-android-push-firebase   File: GraphObjectAdapter.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: myfaces-trinidad   File: SortableModel.java   Source Code and License 6 votes vote down vote up
public Comp(
  ELResolver   resolver,
  ELContext    context,
  Locale       locale,
  String       property,
  SortStrength sortStrength)
{
  _resolver = resolver;
  _context  = context;

  // use Collator as comparator whenever locale or strength is available,
  // so sorting is natural to that locale.
  if (locale != null || sortStrength != null)
  {
    if (locale != null)
      _collator = Collator.getInstance(locale);
    else
      _collator = Collator.getInstance();

    if (sortStrength != null)
      _collator.setStrength(sortStrength.getStrength());
  }
  else
  {
    _collator = null;
  }

  _prop = property;
}
 
Example 18
Project: chromium-for-android-56-debug-video   File: AutofillProfileBridge.java   Source Code and License 6 votes vote down vote up
/** @return The list of supported countries sorted by their localized display names. */
public static List<DropdownKeyValue> getSupportedCountries() {
    List<String> countryCodes = new ArrayList<>();
    List<String> countryNames = new ArrayList<>();
    List<DropdownKeyValue> countries = new ArrayList<>();

    nativeGetSupportedCountries(countryCodes, countryNames);

    for (int i = 0; i < countryCodes.size(); i++) {
        countries.add(new DropdownKeyValue(countryCodes.get(i), countryNames.get(i)));
    }

    final Collator collator = Collator.getInstance(Locale.getDefault());
    collator.setStrength(Collator.PRIMARY);
    Collections.sort(countries, new Comparator<DropdownKeyValue>() {
        @Override
        public int compare(DropdownKeyValue lhs, DropdownKeyValue rhs) {
            int result = collator.compare(lhs.getValue(), rhs.getValue());
            if (result == 0) result = lhs.getKey().compareTo(rhs.getKey());
            return result;
        }
    });

    return countries;
}
 
Example 19
Project: openjdk-jdk10   File: Start.java   Source Code and License 6 votes vote down vote up
void showDocletOptions(Option.Kind kind) {
    Comparator<Doclet.Option> comp = new Comparator<Doclet.Option>() {
        final Collator collator = Collator.getInstance(Locale.US);
        { collator.setStrength(Collator.PRIMARY); }

        @Override
        public int compare(Doclet.Option o1, Doclet.Option o2) {
            return collator.compare(o1.getNames().get(0), o2.getNames().get(0));
        }
    };

    doclet.getSupportedOptions().stream()
            .filter(opt -> opt.getKind() == kind)
            .sorted(comp)
            .forEach(this::showDocletOption);
}
 
Example 20
Project: ramus   File: OwnerClasificators.java   Source Code and License 6 votes vote down vote up
public void updateOuners() {
    List<Qualifier> cls = dataPlugin.getEngine().getQualifiers();
    for (int i = cls.size() - 1; i >= 0; i--) {
        if (IDEF0Plugin.isFunction(cls.get(i)))
            cls.remove(i);
    }
    Collections.sort(cls, new Comparator<Qualifier>() {

        Collator collator = Collator.getInstance();

        @Override
        public int compare(Qualifier o1, Qualifier o2) {
            return collator.compare(o1.getName(), o2.getName());
        }
    });
    cls.remove(dataPlugin.getBaseFunction());
    clasificators = cls.toArray(new Qualifier[cls.size()]);
    String s = dataPlugin.getProperty(DataPlugin.PROPERTY_OUNERS);
    if (s == null)
        s = "";
    final StringTokenizer st = new StringTokenizer(s, " ");
    while (st.hasMoreElements()) {
        owners.add(Long.parseLong(st.nextToken()));
    }
    model.fireTableDataChanged();
}
 
Example 21
Project: openjdk-jdk10   File: VietnameseTest.java   Source Code and License 5 votes vote down vote up
public void TestTertiary() {
    int testLength = testT.length;

    myCollation.setStrength(Collator.TERTIARY);
    for (int i = 0; i < testLength - 1; i++) {
        for (int j = i+1; j < testLength; j++) {
            doTest(myCollation, testT[i], testT[j], -1);
        }
    }
}
 
Example 22
Project: incubator-netbeans   File: ModuleDependency.java   Source Code and License 5 votes vote down vote up
public int compare(ModuleDependency d1, ModuleDependency d2) {
    ModuleEntry me1 = d1.getModuleEntry();
    ModuleEntry me2 = d2.getModuleEntry();
    int result = Collator.getInstance().compare(
            me1.getLocalizedName(), me2.getLocalizedName());
    return result != 0 ? result :
        me1.getCodeNameBase().compareTo(me2.getCodeNameBase());
}
 
Example 23
Project: incubator-netbeans   File: AddModuleFilter.java   Source Code and License 5 votes vote down vote up
/**
 * Find which tokens actually matched a given dependency.
 */
public Set<String> getMatchesFor(String text, ModuleDependency dep) {
    String textLC = text.toLowerCase(Locale.US);
    Set<String> tokens = new TreeSet<String>(Collator.getInstance());
    for (String token : dep.getFilterTokens(dependingModuleCNB)) {
        if (token.toLowerCase(Locale.US).indexOf(textLC) != -1) {
            tokens.add(token);
        }
    }
    return tokens;
}
 
Example 24
Project: Brevent   File: AppsInfo.java   Source Code and License 5 votes vote down vote up
@Override
public int compare(AppsInfo o1, AppsInfo o2) {
    int result = o1.compareTo(o2);
    if (result == 0) {
        long t1 = o1.stats == null ? -1 : o1.stats.getTotalTimeInForeground();
        long t2 = o2.stats == null ? -1 : o2.stats.getTotalTimeInForeground();
        result = Long.compare(t2, t1);
    }
    if (result == 0) {
        result = Collator.getInstance().compare(o1.label, o2.label);
    }
    return result;
}
 
Example 25
Project: OpenJSharp   File: DefaultRowSorter.java   Source Code and License 5 votes vote down vote up
private Comparator getComparator0(int column) {
    Comparator comparator = getComparator(column);
    if (comparator != null) {
        return comparator;
    }
    // This should be ok as useToString(column) should have returned
    // true in this case.
    return Collator.getInstance();
}
 
Example 26
Project: incubator-netbeans   File: Group.java   Source Code and License 5 votes vote down vote up
/**
 * Compares groups according to display name.
 */
public static Comparator<Group> displayNameComparator() {
    return new Comparator<Group>() {
        Collator COLLATOR = Collator.getInstance();
        @Override 
        public int compare(Group g1, Group g2) {
            return COLLATOR.compare(g1.getName(), g2.getName());
        }
    };
}
 
Example 27
Project: openjdk-jdk10   File: FileURLConnection.java   Source Code and License 5 votes vote down vote up
public synchronized InputStream getInputStream()
    throws IOException {

    int iconHeight;
    int iconWidth;

    connect();

    if (is == null) {
        if (isDirectory) {
            FileNameMap map = java.net.URLConnection.getFileNameMap();

            StringBuilder sb = new StringBuilder();

            if (files == null) {
                throw new FileNotFoundException(filename);
            }

            Collections.sort(files, Collator.getInstance());

            for (int i = 0 ; i < files.size() ; i++) {
                String fileName = files.get(i);
                sb.append(fileName);
                sb.append("\n");
            }
            // Put it into a (default) locale-specific byte-stream.
            is = new ByteArrayInputStream(sb.toString().getBytes());
        } else {
            throw new FileNotFoundException(filename);
        }
    }
    return is;
}
 
Example 28
Project: KBUnitTest   File: ShadowDatabaseUtils.java   Source Code and License 5 votes vote down vote up
private static byte[] getCollationKeyInBytes(String name) {
    if (mColl == null) {
        mColl = Collator.getInstance();
        mColl.setStrength(Collator.PRIMARY);
    }
    return mColl.getCollationKey(name).toByteArray();
}
 
Example 29
Project: openjdk-jdk10   File: StringComparable.java   Source Code and License 5 votes vote down vote up
private static final int getMask(final int strength) {
    switch (strength) {
        case Collator.PRIMARY:
            return 0xFFFF0000;
        case Collator.SECONDARY:
            return 0xFFFFFF00;
        default:
            return 0xFFFFFFFF;
    }
}
 
Example 30
Project: grammaticus   File: GrammaticalLocalizer.java   Source Code and License 5 votes vote down vote up
/**
 * @return the Collator for the user's locale.
 * Collators are not threadsafe, so don't reuse this across threads
 */
public Collator getCollator() {
    if (this.collator == null) {
        this.collator = makeCollator();
    }
    return this.collator;
}
 
Example 31
Project: incubator-netbeans   File: Unit.java   Source Code and License 5 votes vote down vote up
public static int compareSourceCategories(Unit u1, Unit u2) {
    if (u1 instanceof Unit.Available && u2 instanceof Unit.Available) {
        Unit.Available unit1 = (Unit.Available)u1;
        Unit.Available unit2 = (Unit.Available)u2;
        return Collator.getInstance().compare(unit1.getSourceDescription(), unit2.getSourceDescription());
    }
    
    throw new IllegalStateException();
}
 
Example 32
Project: OpenJSharp   File: FileURLConnection.java   Source Code and License 5 votes vote down vote up
public synchronized InputStream getInputStream()
    throws IOException {

    int iconHeight;
    int iconWidth;

    connect();

    if (is == null) {
        if (isDirectory) {
            FileNameMap map = java.net.URLConnection.getFileNameMap();

            StringBuffer buf = new StringBuffer();

            if (files == null) {
                throw new FileNotFoundException(filename);
            }

            Collections.sort(files, Collator.getInstance());

            for (int i = 0 ; i < files.size() ; i++) {
                String fileName = files.get(i);
                buf.append(fileName);
                buf.append("\n");
            }
            // Put it into a (default) locale-specific byte-stream.
            is = new ByteArrayInputStream(buf.toString().getBytes());
        } else {
            throw new FileNotFoundException(filename);
        }
    }
    return is;
}
 
Example 33
Project: incubator-netbeans   File: WizardUtils.java   Source Code and License 5 votes vote down vote up
public int compareTo(LayerItemPresenter o) {
    int res = Collator.getInstance().compare(getDisplayName(), o.getDisplayName());
    if (res != 0) {
        return res;
    } else {
        return getFullPath().compareTo(o.getFullPath());
    }
}
 
Example 34
Project: LaunchEnr   File: WidgetItem.java   Source Code and License 5 votes vote down vote up
@Override
public int compareTo(@NonNull WidgetItem another) {
    if (sMyUserHandle == null) {
        // Delay these object creation until required.
        sMyUserHandle = Process.myUserHandle();
        sCollator = Collator.getInstance();
    }

    // Independent of how the labels compare, if only one of the two widget info belongs to
    // work profile, put that one in the back.
    boolean thisWorkProfile = !sMyUserHandle.equals(user);
    boolean otherWorkProfile = !sMyUserHandle.equals(another.user);
    if (thisWorkProfile ^ otherWorkProfile) {
        return thisWorkProfile ? 1 : -1;
    }

    int labelCompare = sCollator.compare(label, another.label);
    if (labelCompare != 0) {
        return labelCompare;
    }

    // If the label is same, put the smaller widget before the larger widget. If the area is
    // also same, put the widget with smaller height before.
    int thisArea = spanX * spanY;
    int otherArea = another.spanX * another.spanY;
    return thisArea == otherArea
            ? Integer.compare(spanY, another.spanY)
            : Integer.compare(thisArea, otherArea);
}
 
Example 35
Project: openjdk-jdk10   File: APITest.java   Source Code and License 5 votes vote down vote up
public final void TestHashCode( )
{
    logln("hashCode tests begin.");
    Collator col1 = null;
    try {
        col1 = Collator.getInstance(Locale.ROOT);
    } catch (Exception foo) {
        errln("Error : " + foo.getMessage());
        errln("Default collation creation failed.");
    }
    Collator col2 = null;
    Locale dk = new Locale("da", "DK", "");
    try {
        col2 = Collator.getInstance(dk);
    } catch (Exception bar) {
        errln("Error : " + bar.getMessage());
        errln("Danish collation creation failed.");
        return;
    }
    Collator col3 = null;
    try {
        col3 = Collator.getInstance(Locale.ROOT);
    } catch (Exception err) {
        errln("Error : " + err.getMessage());
        errln("2nd default collation creation failed.");
    }
    logln("Collator.hashCode() testing ...");

    if (col1 != null) {
        doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect");
        if (col3 != null) {
            doAssert(col1.hashCode() == col3.hashCode(), "Hash result not equal");
        }
    }

    logln("hashCode tests end.");
}
 
Example 36
Project: FlickLauncher   File: AppNameComparator.java   Source Code and License 5 votes vote down vote up
public AppNameComparator(Context context) {
    mCollator = Collator.getInstance();
    mAppInfoComparator = new AbstractUserComparator<ItemInfo>(context) {

        @Override
        public final int compare(ItemInfo a, ItemInfo b) {
            // Order by the title in the current locale
            int result = compareTitles(a.title.toString(), b.title.toString());
            if (result == 0 && a instanceof AppInfo && b instanceof AppInfo) {
                AppInfo aAppInfo = (AppInfo) a;
                AppInfo bAppInfo = (AppInfo) b;
                // If two apps have the same title, then order by the component name
                result = aAppInfo.componentName.compareTo(bAppInfo.componentName);
                if (result == 0) {
                    // If the two apps are the same component, then prioritize by the order that
                    // the app user was created (prioritizing the main user's apps)
                    return super.compare(a, b);
                }
            }
            return result;
        }
    };
    mSectionNameComparator = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return compareTitles(o1, o2);
        }
    };
}
 
Example 37
Project: stynico   File: buff_ext.java   Source Code and License 5 votes vote down vote up
@Override
public int compare(AppInfo lhs, AppInfo rhs)
{
    // 为了适应汉字的比较
    Collator c = Collator.getInstance(Locale.CHINA);
    return (asc == 1) ? c.compare(lhs.appName, rhs.appName)
	: c.compare(rhs.appName, lhs.appName);
}
 
Example 38
Project: openjdk-jdk10   File: Utils.java   Source Code and License 5 votes vote down vote up
private int compareStrings(boolean caseSensitive, String s1, String s2) {
    if (caseSensitive) {
        if (tertiaryCollator == null) {
            tertiaryCollator = new DocCollator(configuration.locale, Collator.TERTIARY);
        }
        return tertiaryCollator.compare(s1, s2);
    }
    if (secondaryCollator == null) {
        secondaryCollator = new DocCollator(configuration.locale, Collator.SECONDARY);
    }
    return secondaryCollator.compare(s1, s2);
}
 
Example 39
Project: VASSAL-src   File: LocaleConfigurer.java   Source Code and License 5 votes vote down vote up
protected String[] getLanguageList() {
  if (languageList == null) {
    String[] langs = Locale.getISOLanguages();
    ArrayList<String> sortedLangs = new ArrayList<String>();
    for (int i = 0; i < langs.length; i++) {
      String lang =
        (new Locale(langs[i])).getDisplayLanguage(Locale.getDefault());
      languages.put(lang, langs[i]);
      sortedLangs.add(lang);
    }
    Collections.sort(sortedLangs, Collator.getInstance(Locale.getDefault()));
    languageList = sortedLangs.toArray(new String[sortedLangs.size()]);
  }
  return languageList;
}
 
Example 40
Project: jdk8u-jdk   File: DefaultRowSorter.java   Source Code and License 5 votes vote down vote up
private Comparator getComparator0(int column) {
    Comparator comparator = getComparator(column);
    if (comparator != null) {
        return comparator;
    }
    // This should be ok as useToString(column) should have returned
    // true in this case.
    return Collator.getInstance();
}