Sort List of Strings with Localization

后端 未结 3 592
心在旅途
心在旅途 2020-11-29 05:31

I want to sort below List of strings as per user locale

List words = Arrays.asList(
      \"Äbc\", \"äbc\", \"Àbc\", \"àbc\", \"Abc\", \"abc\",         


        
相关标签:
3条回答
  • 2020-11-29 05:42
    List<MODEL> ulke = new ArrayList<MODEL>();
    
        Collections.sort(ulke, new Comparator<MODEL>() {
            Collator collator = Collator.getInstance(new Locale("tr-TR"));
            @Override
            public int compare(MODEL o1, MODEL o2) {
                return collator.compare(o1.getULKEAD(), o2.getULKEAD());
            }
        });
    
    0 讨论(0)
  • 2020-11-29 05:45

    You can use a sort with a custom Comparator. See the Collator interface

    Collator coll = Collator.getInstance(locale);
    coll.setStrength(Collator.PRIMARY);
    Collections.sort(words, coll);
    

    The collator is a comparator and can be passed directly to the Collections.sort(...) method.

    0 讨论(0)
  • 2020-11-29 05:45

    I think this what you should be using - Collator

    The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

    Do something as follows in your comparator -

    public int compare(String arg1, Sting arg2) {
        Collator usCollator = Collator.getInstance(Locale.US); //Your locale here
        usCollator.setStrength(Collator.PRIMARY);
        return usCollator.compare(arg1, arg2);
    }
    

    And pass an instance of the comparator the Collections.sort method.

    Update

    Like @Jan Dvorak said, it actually is a comparator, so you can just create it's intance with the desired locale, set the strength and pass it the sort method:

    Collactor usCollator = Collator.getInstance(Locale.US); //Your locale here
    usCollator.setStrength(Collator.PRIMARY); //desired strength
    Collections.sort(yourList, usCollator);
    
    0 讨论(0)
提交回复
热议问题