Sorting a Custom Class Array List String Using Collections.sort Command

I'm trying to sort my own list of arrays of classes using Collections.sort by declaring my own anonymous comparator. But sorting doesn't work as expected.

My code

Collections.sort(arrlstContacts, new Comparator<Contacts>() {

        public int compare(Contacts lhs, Contacts rhs) {

            int result = lhs.Name.compareTo(rhs.Name);

            if(result > 0)
            {
                return 1;

            }
            else if (result < 0)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    });

      

The result is not in sorted order.

+3
java android collections sorting arraylist


source to share


2 answers


As Adam says, just do:

Collections.sort(
  arrlstContacts, 
  new Comparator<Contacts>() 
  {
    public int compare(Contacts lhs, Contacts rhs) 
    {
      return lhs.Name.compareTo(rhs.Name);
    }
  }
);

      



The method String.compareTo

does a lexicographic comparison, which your original code denies. For example, strings number1

and number123

when compared will produce -2 and 2, respectively.

By simply returning 1, 0, or -1, there is a chance (as it is for you) that the merge portion of the merge sort used by the method Collections.sort

may not be able to distinguish enough between the strings in the list, resulting in a list that is not sorted alphabetically.

+9


source to share


As pointed out by Adam, you can use return (lhs.Name.compareTo(rhs.Name));

likeso:



Collections.sort(arrlstContacts, new Comparator<Contacts>() {
     public int compare(Contacts lhs, Contacts rhs) {
         return (lhs.Name.compareTo(rhs.Name));
     }
});

      

+7


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics