0

I have a csv file which includes 3 columns (name,gender,age) and it's irregular(not sorted). I have created a class which name is "Person" and add to a Araylist each column of the csv file by the Person object. Afterthat I wanted to sort this list however it's not sorting. The list occurs as the same the csv file. My code which I expected to sort is below. Could you please check why this code not sorting my list according to age.

Comparator<Person> comparator = new Comparator<Person>() {
            
@Override
        
public int compare(Person first, Person second) {
                if (first.age < second.age) {
                    return first.age;
                } else {
                    return second.age;
                }
            }
        };
        Collections.sort(myList, comparator);
    enter code here

Kind Regards.

  • 2
    as per the javadocs *Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.* – Scary Wombat Sep 08 '21 at 06:26
  • 2
    You need to return something like `Integer.compare(first.age, second.age)` or simply do `first.age - second.age`. As Scary Wombat pointed out, you need to read the Javadoc on `Comparator`. – Thomas Sep 08 '21 at 06:29
  • Can you please give some example and whats the result actually you are getting? – Sivaram Kappaganthu Sep 08 '21 at 07:36

2 Answers2

1

Remove the if else condition.

    Comparator<Person> comparator = new Comparator<Person>() {
        @Override
        public int compare(Person first, Person second) {
            return first.getAge() - second.getAge();
        }
    };
    Collections.sort(persons, comparator);

OR

Java 8

Collections.sort(persons, Comparator.comparingInt(Person::getAge));

Subha Chandra
  • 751
  • 9
  • 23
  • Thank you so much Subha Chandra ; as you typed my Final and Runnable Code : Comparator comparator = new Comparator() { @Override public int compare(Person first, Person second) { return first.Age- second.Age; } }; Collections.sort(myList,comparator); – john dillenger Sep 13 '21 at 11:14
1
myList.sort(Comparator.comparingInt(Person::getAge));

According to the Java doc,

Comparator#compare

Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Ye Jiahao
  • 11
  • 1