Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am looking an algorithm that can map between characters with diacritics (tilde, circumflex, caret, umlaut, caron) and their "simple" character. For example: ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n á --> a ä --> a ấ --> a ṏ --> o etc UPDATE 1) I want to do this in Java, although I suspect it should be something unicode-y and should be doable reasonably easily in an...
I have a question related to Java in my android application. I have a list with some Belgian cities with diacritic characters: (Liège,Quiévrain,Franière, etc.) and I would like to transform these special characters to compare with a list containing the same names in upper case, but without the diacritical marks ( LIEGE, QUIEVRAIN, FRANIERE) What i first tried to do was to use the upper case: ...
I have a (array) list Car Something Šibica Čavao Cavao Is there a way to "force" AutoCompleteTextView so if user type in letter "c" it would show Car Čavao Cavao so it would show standard letter and international letter (C and Č/Ć, S and Š, Z and Ž, D and Đ).
More specifically I want an interface to compare objects which can be only compared for equality [e.g. complex numbers] but don't have total order on them. It should have [Note that it only returns a boolean yes/no] boolean Equals(T object1, T object2); and a hashcode function. So that when I distribute them into buckets using objects say to collect "equal" objects, 2 "equal" objects don't ...
I am working at the moment with some data in hungarians. I have to sort a list of hungarians strings. According to this Collation Sequence page Hungarian alphabetic order is: A=Á, B, C, CS, D, DZ, DZS, E=É, F, G, GY, H, I=Í, J, K, L, LY, M, N, NY, O=Ó, Ö=Ő, P, Q, R, S, SZ, T, TY, U=Ú, Ü=Ű, V, W, X, Y, Z, ZS So vowels are treated the same (A=Á, ...) so in the result you can have some ...
Short Version I'm currently looking into an issue with MySQL collations and how they affect a Set of values (which is mapped using Hibernate, but that shouldn't matter for now). I want to have a Set of Strings using the same collation as MySQL uses. E.g. I want "foobar" and "fööbar" considered equal but "foo bar" and "foobar" considered different. Using default Collator.getInstance() (with Col...
I need a multi map which keys are case insensitive. is there such implementation in google collections?
I'm making a Java app that receives some names from SQLite and puts them on a listbox. The thing is I want it to be accurately ordered in an ascending alphabetical way (In Portuguese to be specific). These entries, for example: Beta Árida Ana Should be ordered as: Ana Árida Beta But since it orders in some ASCII order, the "accented" characters on will be thrown at the end and not right be...
I have a list of String characters, They are mix characters that includes special characters too. I want to know how to sort them ascendingly ? updated example aplha1.jpg aplha10.jpg 2.jpg 3.jpg 4.jpg aplha5.jpg
I am writing a program to sort Spanish words.The letters are almost the same as the English alphabet, only with a few exceptions. a,b,c,ch,d,e,f,g,h,i,j,k,l,ll,m,n,ñ,o,p,q,r,rr,s,t,u,v,w,x,y,z Further, for this problem, assume that any pair of characters which can represent a letter does; for example, the combination ch would always mean the letter ch, not the letter c followed by the letter...
I tried to type char literals for accentuated vowels in Java, but the compilers says something like: unclosed character literal This is what I'm trying to do: char [] a = {'à', 'á', 'â', 'ä' }; I've tried using Unicode '\u00E0' but for some reason they don't match with my code: for( char c : string.toCharArray() ) { if( c == a[i] ) { // I've found a funny letter } } ...
How is the lexicographic order defined in Java especially in reference to special characters like !, . and so on? As an example does Sheepsystems offers this order But how does Java define it's order? I ask because I'm sorting Strings on Java and on Oracle and come up with different results and can't find the specification for the lexicographic order.
I want to compare two strings with the method string.compareTo(anOtherString); and it delivers me a strange value... (i need an integer value between 0 and 57 for every string) In the following example the first line delivers 2 and the second 1. System.out.println("And".compareTo("A")); System.out.println("Bus".compareTo("A")); I expected that the first line is 1 and the second 2... ...
I have written this code and don't know how to sort surnames in alphabetical order from my file to another file. import java.io.*; import java.util.*; class Asmuo { String pavarde; String vardas; long buvLaikas; int atv1; int atv2; int atv3; } class Irasas { Asmuo duom; Irasas kitas; } class Sarasas { private Irasas p; Sarasas() { p = null;...
Well, I tested TreeMap but it doesn't take in account IgnoreCase on string comparision. I need to order lexicographically and ignoring case. Is there any other way? Thanks, that works (TreeMap (Comparator c)). However, I have another question: public final Comparator<Object> STR_IGN_CASE_COMP = new Comparator<Object>() { public int compare(Object h1, Object h2) { ...
  /*
   * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 /*
  * (C) Copyright Taligent, Inc. 1996-1998 -  All Rights Reserved
  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  *
  *   The original version of this source code and documentation is copyrighted
  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  * materials are provided under terms of a License Agreement between Taligent
  * and Sun. This technology is protected by multiple US and International
  * patents. This notice and attribution to Taligent may not be removed.
  *   Taligent is a registered trademark of Taligent, Inc.
  *
  */
 
 package java.text;
 
The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

Collator is an abstract base class. Subclasses implement specific collation strategies. One subclass, RuleBasedCollator, is currently provided with the Java Platform and is applicable to a wide set of languages. Other subclasses may be created to handle more specialized needs.

Like other locale-sensitive classes, you can use the static factory method, getInstance, to obtain the appropriate Collator object for a given locale. You will only need to look at the subclasses of Collator if you need to understand the details of a particular collation strategy or if you need to modify that strategy.

The following example shows how to compare two strings using the Collator for the default locale.

 // Compare two strings in the default locale
 Collator myCollator = Collator.getInstance();
 if( myCollator.compare("abc", "ABC") < 0 )
     System.out.println("abc is less than ABC");
 else
     System.out.println("abc is greater than or equal to ABC");
 

You can set a Collator's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY, SECONDARY, TERTIARY, and IDENTICAL. The exact assignment of strengths to language features is locale dependant. For example, in Czech, "e" and "f" are considered primary differences, while "e" and "ě" are secondary differences, "e" and "E" are tertiary differences and "e" and "e" are identical. The following shows how both case and accents could be ignored for US English.

 //Get the Collator for US English and set its strength to PRIMARY
 Collator usCollator = Collator.getInstance(Locale.US);
 usCollator.setStrength(Collator.PRIMARY);
 if( usCollator.compare("abc", "ABC") == 0 ) {
     System.out.println("Strings are equivalent");
 }
 

For comparing Strings exactly once, the compare method provides the best performance. When sorting a list of Strings however, it is generally necessary to compare each String multiple times. In this case, CollationKeys provide better performance. The CollationKey class converts a String to a series of bits that can be compared bitwise against other CollationKeys. A CollationKey is created by a Collator object for a given String.
Note: CollationKeys from different Collators can not be compared. See the class description for CollationKey for an example using CollationKeys.

Author(s):
Helena Shih, Laura Werner, Richard Gillam
See also:
RuleBasedCollator
CollationKey
CollationElementIterator
java.util.Locale
public abstract class Collator
    implements java.util.Comparator<Object>, Cloneable
{
    
Collator strength value. When set, only PRIMARY differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for different base letters ("a" vs "b") to be considered a PRIMARY difference.

    public final static int PRIMARY = 0;
    
Collator strength value. When set, only SECONDARY and above differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for different accented forms of the same base letter ("a" vs "\u00E4") to be considered a SECONDARY difference.

    public final static int SECONDARY = 1;
    
Collator strength value. When set, only TERTIARY and above differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for case differences ("a" vs "A") to be considered a TERTIARY difference.

    public final static int TERTIARY = 2;

    
Collator strength value. When set, all differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for control characters ("\u0001" vs "\u0002") to be considered equal at the PRIMARY, SECONDARY, and TERTIARY levels but different at the IDENTICAL level. Additionally, differences between pre-composed accents such as "\u00C0" (A-grave) and combining accents such as "A\u0300" (A, combining-grave) will be considered significant at the IDENTICAL level if decomposition is set to NO_DECOMPOSITION.
    public final static int IDENTICAL = 3;

    
Decomposition mode value. With NO_DECOMPOSITION set, accented characters will not be decomposed for collation. This is the default setting and provides the fastest collation but will only produce correct results for languages that do not use accents.

    public final static int NO_DECOMPOSITION = 0;

    
Decomposition mode value. With CANONICAL_DECOMPOSITION set, characters that are canonical variants according to Unicode standard will be decomposed for collation. This should be used to get correct collation of accented characters.

CANONICAL_DECOMPOSITION corresponds to Normalization Form D as described in Unicode Technical Report #15.

    public final static int CANONICAL_DECOMPOSITION = 1;

    
Decomposition mode value. With FULL_DECOMPOSITION set, both Unicode canonical variants and Unicode compatibility variants will be decomposed for collation. This causes not only accented characters to be collated, but also characters that have special formats to be collated with their norminal form. For example, the half-width and full-width ASCII and Katakana characters are then collated together. FULL_DECOMPOSITION is the most complete and therefore the slowest decomposition mode.

FULL_DECOMPOSITION corresponds to Normalization Form KD as described in Unicode Technical Report #15.

    public final static int FULL_DECOMPOSITION = 2;

    
Gets the Collator for the current default locale. The default locale is determined by java.util.Locale.getDefault.

Returns:
the Collator for the default locale.(for example, en_US)
See also:
java.util.Locale.getDefault()
    public static synchronized Collator getInstance() {
        return getInstance(Locale.getDefault());
    }

    
Gets the Collator for the desired locale.

Parameters:
desiredLocale the desired locale.
Returns:
the Collator for the desired locale.
See also:
java.util.Locale
java.util.ResourceBundle
    public static synchronized
    Collator getInstance(Locale desiredLocale)
    {
        Collator result = (Collator.get(desiredLocale);
        if (result != null) {
                 return (Collator)result.clone();  // make the world safe
        }
        // Check whether a provider can provide an implementation that's closer
        // to the requested locale than what the Java runtime itself can provide.
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(CollatorProvider.class);
        if (pool.hasProviders()) {
            Collator providersInstance = pool.getLocalizedObject(
                                            .,
                                            desiredLocale,
                                            desiredLocale);
            if (providersInstance != null) {
                return providersInstance;
            }
        }
        // Load the resource of the desired locale from resource
        // manager.
        String colString = "";
        try {
            ResourceBundle resource = LocaleData.getCollationData(desiredLocale);
            colString = resource.getString("Rule");
        } catch (MissingResourceException e) {
            // Use default values
        }
        try
        {
            result = new RuleBasedCollator. +
                                            colString,
                                             );
        }
        catch(ParseException foo)
        {
            // predefined tables should contain correct grammar
            try {
                result = new RuleBasedCollator. );
            } catch (ParseException bar) {
                // do nothing
            }
        }
        // Now that RuleBasedCollator adds expansions for pre-composed characters
        // into their decomposed equivalents, the default collators don't need
        // to have decomposition turned on.  Laura, 5/5/98, bug 4114077
        result.setDecomposition();
        .put(desiredLocale,result);
        return (Collator)result.clone();
    }

    
Compares the source string to the target string according to the collation rules for this Collator. Returns an integer less than, equal to or greater than zero depending on whether the source String is less than, equal to or greater than the target string. See the Collator class description for an example of use.

For a one time comparison, this method has the best performance. If a given String will be involved in multiple comparisons, CollationKey.compareTo has the best performance. See the Collator class description for an example using CollationKeys.

Parameters:
source the source string.
target the target string.
Returns:
Returns an integer value. Value is less than zero if source is less than target, value is zero if source and target are equal, value is greater than zero if source is greater than target.
See also:
CollationKey
getCollationKey(java.lang.String)
    public abstract int compare(String sourceString target);

    
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

This implementation merely returns compare((String)o1, (String)o2) .

Returns:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Throws:
java.lang.ClassCastException the arguments cannot be cast to Strings.
Since:
1.2
See also:
java.util.Comparator
    public int compare(Object o1Object o2) {
    return compare((String)o1, (String)o2);
    }

    
Transforms the String into a series of bits that can be compared bitwise to other CollationKeys. CollationKeys provide better performance than Collator.compare when Strings are involved in multiple comparisons. See the Collator class description for an example using CollationKeys.

Parameters:
source the string to be transformed into a collation key.
Returns:
the CollationKey for the given String based on this Collator's collation rules. If the source String is null, a null CollationKey is returned.
See also:
CollationKey
compare(java.lang.String,java.lang.String)
    public abstract CollationKey getCollationKey(String source);

    
Convenience method for comparing the equality of two strings based on this Collator's collation rules.

Parameters:
source the source string to be compared with.
target the target string to be compared with.
Returns:
true if the strings are equal according to the collation rules. false, otherwise.
See also:
compare(java.lang.String,java.lang.String)
    public boolean equals(String sourceString target)
    {
        return (compare(sourcetarget) == .);
    }

    
Returns this Collator's strength property. The strength property determines the minimum level of difference considered significant during comparison. See the Collator class description for an example of use.

Returns:
this Collator's current strength property.
See also:
setStrength(int)
PRIMARY
SECONDARY
TERTIARY
IDENTICAL
    public synchronized int getStrength()
    {
        return ;
    }

    
Sets this Collator's strength property. The strength property determines the minimum level of difference considered significant during comparison. See the Collator class description for an example of use.

Parameters:
newStrength the new strength value.
Throws:
java.lang.IllegalArgumentException If the new strength value is not one of PRIMARY, SECONDARY, TERTIARY or IDENTICAL.
See also:
getStrength()
PRIMARY
SECONDARY
TERTIARY
IDENTICAL
    public synchronized void setStrength(int newStrength) {
        if ((newStrength != ) &&
            (newStrength != ) &&
            (newStrength != ) &&
            (newStrength != ))
            throw new IllegalArgumentException("Incorrect comparison level.");
         = newStrength;
    }

    
Get the decomposition mode of this Collator. Decomposition mode determines how Unicode composed characters are handled. Adjusting decomposition mode allows the user to select between faster and more complete collation behavior.

The three values for decomposition mode are:

  • NO_DECOMPOSITION,
  • CANONICAL_DECOMPOSITION
  • FULL_DECOMPOSITION.
See the documentation for these three constants for a description of their meaning.

    public synchronized int getDecomposition()
    {
        return ;
    }
    
Set the decomposition mode of this Collator. See getDecomposition for a description of decomposition mode.

Parameters:
decompositionMode the new decomposition mode.
Throws:
java.lang.IllegalArgumentException If the given value is not a valid decomposition mode.
See also:
getDecomposition()
NO_DECOMPOSITION
CANONICAL_DECOMPOSITION
FULL_DECOMPOSITION
    public synchronized void setDecomposition(int decompositionMode) {
        if ((decompositionMode != ) &&
            (decompositionMode != ) &&
            (decompositionMode != ))
            throw new IllegalArgumentException("Wrong decomposition mode.");
         = decompositionMode;
    }

    
Returns an array of all locales for which the getInstance methods of this class can return localized instances. The returned array represents the union of locales supported by the Java runtime and by installed CollatorProvider implementations. It must contain at least a Locale instance equal to Locale.US.

Returns:
An array of locales for which localized Collator instances are available.
    public static synchronized Locale[] getAvailableLocales() {
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(CollatorProvider.class);
        return pool.getAvailableLocales();
    }

    
Overrides Cloneable
    public Object clone()
    {
        try {
            return (Collator)super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    
Compares the equality of two Collators.

Parameters:
that the Collator to be compared with this.
Returns:
true if this Collator is the same as that Collator; false otherwise.
    public boolean equals(Object that)
    {
        if (this == thatreturn true;
        if (that == nullreturn false;
        if (getClass() != that.getClass()) return false;
        Collator other = (Collatorthat;
        return (( == other.strength) &&
                ( == other.decmp));
    }

    
Generates the hash code for this Collator.
    abstract public int hashCode();

    
Default constructor. This constructor is protected so subclasses can get access to it. Users typically create a Collator sub-class by calling the factory method getInstance.

See also:
getInstance()
    protected Collator()
    {
         = ;
         = ;
    }
    private int strength = 0;
    private int decmp = 0;
    private static SoftCache cache = new SoftCache();
    //
    // FIXME: These three constants should be removed.
    //
    
LESS is returned if source string is compared to be less than target string in the compare() method.

    final static int LESS = -1;
    
EQUAL is returned if source string is compared to be equal to target string in the compare() method.

    final static int EQUAL = 0;
    
GREATER is returned if source string is compared to be greater than target string in the compare() method.

    final static int GREATER = 1;

    
Obtains a Collator instance from a CollatorProvider implementation.
    private static class CollatorGetter
        private static final CollatorGetter INSTANCE = new CollatorGetter();
        public Collator getObject(CollatorProvider collatorProvider,
                                Locale locale,
                                String key,
                                Object... params) {
            assert params.length == 1;
            Collator result = collatorProvider.getInstance(locale);
            if (result != null) {
                // put this Collator instance in the cache for two locales, one
                // is for the desired locale, and the other is for the actual
                // locale where the provider is found, which may be a fall back locale.
                .put((Locale)params[0], result);
                .put(localeresult);
                return (Collator)result.clone();
            }
            return null;
        }
    }
 }
New to GrepCode? Check out our FAQ X