I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.
For example my inp
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 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() {
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();