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
// Sort Without using Comparator
import java.util.ArrayList; import java.util.List;
public class SortByNameThenAge {
static class Student {
String name;
int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
public static void main(String[] args) {
List<Student> olist = new ArrayList<>();
olist.add(new Student("Sam", 26));
olist.add(new Student("Sam", 22));
olist.add(new Student("Abc", 25));
olist.add(new Student("Abc", 22));
olist.add(new Student("Abc", 23));
olist.add(new Student("Sam", 24));
olist.add(new Student("Sam2", 21));
olist.add(new Student("Sam2", 19));
// Order By name
for (int i = 0; i < olist.size(); i++) {
for (int j = olist.size() - 1; j > i; j--) {
if (olist.get(i).name.compareTo(olist.get(j).name) > 0) {
Student temp = olist.get(i);
olist.set(i, olist.get(j));
olist.set(j, temp);
}
}
}
for (Student s : olist) {
System.out.println(s.name + " : " + s.age);
}
// Order by name then age
for (int i = 0; i < olist.size(); i++) {
for (int j = i+1; j < olist.size(); j++) {
if (olist.get(i).name.compareTo(olist.get(j).name) == 0) {
if (olist.get(i).age > olist.get(i + 1).age) {
Student temp = olist.get(i);
olist.set(i, olist.get(i + 1));
olist.set(i + 1, temp);
}
}
}
}
System.out.println("\nSorting by age keeping name as it is");
for (Student s : olist) {
System.out.println(s.name + " : " + s.age);
}
}
}
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:
t.getFname().compareTo(t1.getFname())
Proper way of comparing integers is with the static Integer.compare method, i.e. Integer.compare(t.getAge(), t1.getAge())
.