How to sort the name along with age in java

Currently you are a) only comparing by one attribute and b) not really making use of Java 8's new features.

With Java 8 you can use method references and chained comparators, like this:

Collections.sort(persons, Comparator.comparing(Person::getFname)
    .thenComparingInt(Person::getAge));

This will compare two Person instances first by their fname and - if that is equal - by their age (with a slight optimization to thenComparingInt to avoid boxing).


Your Comparator is only sorting by age, not by name.

You could try it like that:

new Comparator<Person>() {
    @Override
    public int compare(Person t, Person t1) {
        int ret = t.getFname().compareTo(t1.getFname());
        if (ret == 0) {
           ret = Integer.compare(t.getAge(), t1.getAge()); 
        }
        return ret;
    }
}

You could also think about implementing Comparable<Person> in the Person class itself:

class Person implements Comparable<Person> {
    @Override
    public int compareTo(Person p) {
        int ret = fname.compareTo(p.fname);
        if (ret == 0) {
           ret = Integer.compare(age, p.getAge()); 
        }
        return ret;

    }
}

You are on the right path, but your compare method is incomplete.

Since compare is called to decide which item in each pair is to go before the other, it must include all comparison logic, not only the tie-breaking one. Your code sorts on the age alone, ignoring the name completely.

The logic should go like this:

  • Compare names using t.getFname().compareTo(t1.getFname())
  • If names are not the same, return the result of comparison
  • Otherwise, return the result of comparing ages.

Proper way of comparing integers is with the static Integer.compare method, i.e. Integer.compare(t.getAge(), t1.getAge()).


You need to compare for names first. If the names are the same, then and only then the result depends on comparing the age

public static void main(String[] args) {
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("tarun", 28));
    persons.add(new Person("arun", 29));
    persons.add(new Person("varun", 12));
    persons.add(new Person("arun", 22));

    Collections.sort(persons, new Comparator<Person>() {

        public int compare(Person t, Person t1) {
            int comp = t.getFname().compareTo(t1.getFname());
            if (comp != 0) {    // names are different
                return comp;
            }
            return t.getAge() - t1.getAge();
        }
    });
    System.out.println(persons);

}}

if you want to change from ascending to descending, just change the sign. e.g.

 return -comp;

or swap the person

name

 int comp = t1.getFname().compareTo(t.getFname());

age

 return t1.getAge() - t.getAge();