0

I have This method below which works for sorting out Student objects in an arraylist using String parameters, for example a Student Object would have a String name,int age and String course parameter

//This Sorts with String parameters
public void sortArrayListByName()
{
    Collections.sort(sList,new Comparator<Student>() {
         public int compare(Student s1, Student s2) {
                 return s1.getName().compareTo(s2.getName());
         }
     });
}

Now I want to implement this code with integer parameters

//This should sort the Arraylist of Objects
public void sortArrayListByAge()
{
    Collections.sort(sList,new Comparator<Student>() {
         public int compare(Student s1, Student s2) {
                 return s1.getAge().compareToIgnoreCase(s2.getAge()); //This Part gives me errors
         }
     });
}

But i get an error message saying Cannot invoke compareToIgnoreCase(int) on the primitive type int

How can i fix this code so that it will be able to sort the list with integer values?

2
  • 1
    If age in the Student class is of type int then just use a simple equality comparison operator. Commented Aug 14, 2014 at 17:11
  • ints are not Strings. Commented Aug 14, 2014 at 17:12

5 Answers 5

3

You're comparing int values, which are primitive types and int does not have any methods. This is why s1.getAge().compareToIgnoreCase(s2.getAge()) fails.

If you happen to use Java 7 or prior, use Integer#compare:

public int compare(Student s1, Student s2) {
    return Integer.compare(s1.getAge(), s2.getAge()); 
}

Otherwise, compare the int variables manually (code adapted from Integer#compare source, there's no need to reinvent the wheel):

public int compare(Student s1, Student s2) {
    return (s1.getAge() < s2.getAge()) ? -1 : ((s1.getAge() == s2.getAge()) ? 0 : 1); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

haha yea, this works, i don't know why i didn't think of that, thanks for your input
Take care to check for null on either of your objects or this solution could break.
@RyanJ if there's a NPE I would not worry on this method but why I added null elements in the list.
2

Try this:

//This should sort the Arraylist of Objects
public void sortArrayListByAge()
{
    Collections.sort(sList,new Comparator<Student>() {
         public int compare(Student s1, Student s2) {
                 int result = 0;   // assume equal
                 if ( (s1 == null && s2 != null )|| (s1.getAge() > s2.getAge()) ) {
                     result = 1;
                 }
                 if ( (s1 != null && s2 == null) || s1.getAge() < s2.getAge() ) {
                     result = -1;
                 }
                 return result;
         }
     });
}

Comments

2

You already got your answer, but one of the options is to also use sorted method from Java 8 Stream API:

sList.stream().sorted((s1, s2) -> Integer.compare(s1.getAge(), s2.getAge()))
              .forEach(s -> System.out.println(s.getName() + ", " + s.getAge()));

Comments

0

You can use normal comparison operators :

public void sortArrayListByAge()
{
    Collections.sort(sList,new Comparator<Student>() {
         public int compare(Student s1, Student s2) {
                 if (s1 != null && s2 != null) {
                    if (s1.getAge() < s2.getAge())
                        return -1;
                    else {
                        if (s1.getAge() > s2.getAge())
                            return 1;
                        else
                            return 0;
                    }
                 } else if (s1 != null) {
                    return 1; // s2 is null
                 } else if (s2 != null) {
                    return -1; // s1 is null
                 } else {
                    return 0; // both s1 and s2 are null
                 }
         }
     });

}

2 Comments

Wouldn't it be the other way? (I think you mixed up negative and positive returns.)
@Jashaszun a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. - I think I got it right.
0

The compareTo and compareToIgnoreCase methods are inverted.

To sort integers, like age, use:

return s1.getAge().compareTo(s2.getAge());

And to sort Strings, like names, and ignoring the case, use:

return s1.getName().compareToIgnoreCase(s2.getName());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.