1

I have a List of Objects List<Student>.

class Student {
 private String name;
 private Integer age;
 private Integer rank

 public String getName() {
  return this.name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return this.name;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 public Integer getRank() {
  return this.rank;
 }
 public void getRank(Integer rank) {
  this.rank = rank;
 }
}

I have to sort List based on rank first, if two students have same rank then based on their age and if their age is same then based on their name.

Can any one help? Thanks

1
  • 1
    Either create a Comparator<Student, Student> or have Student implement Comparable<Student> and then define your comparison logic in there. Either way, you can then use Java's builtin sorting capabilities. Commented May 27, 2017 at 17:26

3 Answers 3

1

You can use java8 lambdas

List<Student> students = new Arraylist<>();
...
...
...
student.sort()

students.sort(Comparator.comparing(Student::getName).thenComparing(Student::getAge));
Sign up to request clarification or add additional context in comments.

1 Comment

I suppose you mean Java8 since lamdas introduced in Java8 and Student::getName is illegal in Java7
0

In java8 you have .thenComparing(...) method

Comparator< Student> studentComparator = Comparator.comparing(student -> student.name);
comparator = comparator.thenComparing(Comparator.comparing(student -> student.age));
comparator = comparator.thenComparing(Comparator.comparing(student -> student.rank));

 // Then pass this comparator in Collections#sort method

Collecions.sort(studentList, studentComparator); Your list will be sorted

Comments

0

You can use Guava for Java 7 for same use case .

See: https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#compare/compareTo.md

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.