Using Object Oriented Programming approach
public class Student {
private String name;
private int marks;
Student(String name, int marks){
this.name = name;
this.marks = marks;
}
public String getName() {
return name;
}
public int getMarks() {
return marks;
}
}
public class Result {
public static List<Student> getResult(List<Student> personList){
personList.sort(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getMarks() - s2.getMarks();
}
});
return personList;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Bob", 32));
studentList.add(new Student("Carol", 43));
studentList.add(new Student("Alice", 12));
studentList.add(new Student("Dave", 57));
studentList.add(new Student("Eve", 64));
studentList = Result.getResult(studentList);
System.out.println("Student list according to result");
for(Student student: studentList){
System.out.println("Name: "+student.getName());
}
}
}
Using Lambda Expression
public class Student {
private String name;
private int marks;
Student(String name, int marks){
this.name = name;
this.marks = marks;
}
public String getName() {
return name;
}
public int getMarks() {
return marks;
}
}
public class Main {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Bob", 32));
studentList.add(new Student("Carol", 43));
studentList.add(new Student("Alice", 12));
studentList.add(new Student("Dave", 57));
studentList.add(new Student("Eve", 64));
studentList.sort((Student s1, Student s2) -> s1.getMarks()- s2.getMarks());
System.out.println("Person list In Sorted Order");
for (Student student: studentList){
System.out.println(student.getName());
}
}
}