We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Scanner sc = new Scanner(System.in);
Comparator<Student> com = new Comparator<>(){
public int compare(Student i, Student j){
if(i.age<j.age){
return 1;
}else if(i.age > j.age) {
return -1;
}else{
return i.name.compareTo(j.name);
}
}
};
int n = sc.nextInt();
List<Student> student = new ArrayList<>();
for(int i=0;i<n;i++){
String name = sc.next();
int age = sc.nextInt();
student.add(new Student(name,age));
}
Collections.sort(student,com);
for(Student a : student){
System.out.println(a.name +" " + a.age);
}
}
}
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Comparator
You are viewing a single comment's thread. Return to all comments →
} }
class Student { String name; int age;
public Student(String name, int age) { this.name = name; this.age = age; } }