How to sort a List<Object> alphabetically using Object name field

后端 未结 16 1349
暗喜
暗喜 2020-11-28 06:00

I have a List of Objects like List p.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is o
相关标签:
16条回答
  • 2020-11-28 06:01
    if(listAxu.size() > 0){
         Collections.sort(listAxu, new Comparator<Situacao>(){
            @Override
            public int compare(Situacao lhs, Situacao rhs) {            
                return lhs.getDescricao().compareTo(rhs.getDescricao());
            }
        });
     }
    
    0 讨论(0)
  • 2020-11-28 06:02

    The most correct way to sort alphabetically strings is to use Collator, because of internationalization. Some languages have different order due to few extra characters etc.

       Collator collator = Collator.getInstance(Locale.US);
       if (!list.isEmpty()) {
        Collections.sort(list, new Comparator<Campaign>() {
            @Override
            public int compare(Campaign c1, Campaign c2) {
                //You should ensure that list doesn't contain null values!
                return collator.compare(c1.getName(), c2.getName());
            }
           });
       }
    

    If you don't care about internationalization use string.compare(otherString).

       if (!list.isEmpty()) {
        Collections.sort(list, new Comparator<Campaign>() {
            @Override
            public int compare(Campaign c1, Campaign c2) {
                //You should ensure that list doesn't contain null values!
                return c1.getName().compare(c2.getName());
            }
           });
       }
    
    0 讨论(0)
  • 2020-11-28 06:03

    If your objects has some common ancestor [let it be T] you should use List<T> instead of List<Object>, and implement a Comparator for this T, using the name field.

    If you don't have a common ancestor, you can implement a Comperator, and use reflection to extract the name, Note that it is unsafe, unsuggested, and suffers from bad performance to use reflection, but it allows you to access a field name without knowing anything about the actual type of the object [besides the fact that it has a field with the relevant name]

    In both cases, you should use Collections.sort() to sort.

    0 讨论(0)
  • 2020-11-28 06:08

    I found another way to do the type.

    if(listAxu.size() > 0){
        Collections.sort(listAxu, Comparator.comparing(IdentityNamed::getDescricao));
    }
    
    0 讨论(0)
  • 2020-11-28 06:11

    something like

      List<FancyObject> theList = … ;
      Collections.sort (theList,
                        new Comparator<FancyObject> ()
                        { int compare (final FancyObject a, final FancyObject d)
                              { return (a.getName().compareTo(d.getName())); }});
    
    0 讨论(0)
  • 2020-11-28 06:15

    Using Java 8 Comparator.comparing:

    list.sort(Comparator.comparing(Campaign::getName));
    
    0 讨论(0)
提交回复
热议问题