Sort in Descending Order using Comparator and Comparable

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
* Sort in Descending Order using Comparator and Comparable
*
* @author asharda
*
*/
class Student implements Comparator<Student>, Comparable<Student> {

int marks;
String name;

public Student() {

}

public Student(String n, int m) {
name = n;
marks = m;
}

public String getName() {
return name;
}

public int getMarks() {
return marks;
}

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o2.marks – o1.marks;
}

@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return o.name.compareTo(name);
}

}

public class StudentTest {
public static void main(String args[]) {
List<Student> list1 = new ArrayList<Student>();
list1.add(new Student(“Ashish”, 82));
list1.add(new Student(“Sai”, 100));
Collections.sort(list1);
for (Student s : list1)
System.out.println(“Name is ” + s.getName() + “Marks are ” + s.getMarks());
}
}

Advertisements

About qainterviews

Software Geek,QA Expert,Blogger
This entry was posted in Java, Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s