pawan sharma pawan sharma - 1 month ago 11
Java Question

How to sort the name along with age in java

I am new to Java 8 . I just want to sort the the name. but the condition is if there are duplicate name then it should be sorted according to age.

for example my input is

tarun 28
arun 29
varun 12
arun 22

and output should be
arun 22
arun 29
tarun 28
varun 12

but i got something like
varun 12
arun 22
tarun 28
arun 29

Means its sorted either only by ages or names

this is code which is implemented

POJO Class..

class Person {

String fname;

int age;

public Person() {
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getFname() {
return fname;
}

public void setFname(String fname) {
this.fname = fname;
}



public Person(String fname, int age) {
this.fname = fname;

this.age = age;
}

@Override
public String toString() {
return fname + age;
}}


This is Test Class

public class Test{

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>() {

@Override
public int compare(Person t, Person t1) {
return t.getAge() - t1.getAge();
}
});
System.out.println(persons);

}}

Answer Source

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).