Android : How To Sort An Arraylist of Special Char

2019-07-08 20:45发布

I am developing an android application where i have data in Norwegian language. Now , i have to sort a list of name alphabetically where the names contain special norwegian characters.

    Comparator<SetGetMethods> comperator = new Comparator<SetGetMethods>() {

        public int compare(SetGetMethods object1, SetGetMethods object2) {

                return object1.getCityname().compareToIgnoreCase(object2.getCityname());

        }

    };
    Collections.sort(temp, comperator);

I used the code above to sort the list alphabetically. But after sorting , the names with normal characters shown on top and names with special norwegian characters shown below them. For example , the list is shown like below ,

Arendal Bergen Drammen Ålesund -> ( This should be on top , before Arendal after sorting )

So , my question is , how can i sort a list alphabetically where the list data contains special characters(Norwegian characters). I will appreciate any suggestion , idea or sample code to solve the problem. Thanks .....

3条回答
太酷不给撩
2楼-- · 2019-07-08 21:33

Use a Collator. This is a type of Comparator that performs locale-sensitive String comparison.

Without knowing about the Norwegian language/characters, I think you'd want to use the following code:

Collator noCollator = Collator.getInstance(new Locale("no", "NO"));
noCollator.setStrength(Collator.SECONDARY);
...
查看更多
祖国的老花朵
3楼-- · 2019-07-08 21:38

Take a look at the example based on Norwegian in the JavaDoc for the RuleBasedCollator class.

Based on that, I've created this example that puts Å before A based on a accent difference -- note the use of ';' to put \u00E5 before A. So this works for your example input, but you'll need to add other accented Norwegian characters based on your knowledge of the language to complete the norwegian comparison string.

String norwegian = "< a, \u00E5;A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
                   "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
                   "< u,U< v,V< w,W< x,X< y,Y< z,Z";                      
RuleBasedCollator myNorwegian = new RuleBasedCollator(norwegian);     
List<String> words = 
  Arrays.asList("Arendal Bergen Drammen \u00E5lesund".split("\\s"));     
System.out.println(words);     
Collections.sort(words, myNorwegian);     
System.out.println(words);
查看更多
贼婆χ
4楼-- · 2019-07-08 21:42

Try this

For an Object

class MyObject
{
  public String name;
  public int score;
}

If you want to order by name (in this case using Norwegian language), you can do this

Locale locale = new Locale("nb", "NO");
final Collator collator = java.text.Collator.getInstance(locale);

Collections.sort(your_array, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject obj1, MyObject obj2) {
        return collator.compare(obj1.name, obj2.name);            
    }
});
查看更多
登录 后发表回答