Guest User

Untitled

a guest
Nov 17th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class Algorithms {
  7. private static class Student implements Comparable<Student> {
  8. private float grade;
  9. private String name;
  10.  
  11. @Override
  12. public int compareTo(Student student) {
  13. return Float.compare(grade, student.grade);
  14. }
  15.  
  16. public float getGrade() {
  17. return grade;
  18. }
  19.  
  20. public String getName() {
  21. return name;
  22. }
  23.  
  24. public Student(String name, float grade) {
  25.  
  26. this.grade = grade;
  27. this.name = name;
  28. }
  29.  
  30. @Override
  31. public String toString() {
  32. return "Student{" +
  33. "grade=" + grade +
  34. ", name='" + name + '\'' +
  35. '}';
  36. }
  37. }
  38.  
  39. private static void printStudents(Collection<Student> collection) {
  40. for (Student student : collection) {
  41. System.out.println(student);
  42. }
  43. }
  44.  
  45. public static void main(String[] args) {
  46. ArrayList<Student> students = new ArrayList<>();
  47.  
  48. students.add(new Student("Serban", 9.3f));
  49. students.add(new Student("Nicolae", 5.3f));
  50. students.add(new Student("Ion", 7.3f));
  51.  
  52. System.out.println("Initial");
  53. printStudents(students);
  54.  
  55. Collections.sort(students);
  56.  
  57. System.out.println("Sortati dupa nota");
  58. printStudents(students);
  59.  
  60. Collections.sort(students, new Comparator<Student>() {
  61. @Override
  62. public int compare(Student student, Student t1) {
  63. return -student.getName().compareTo(t1.getName());
  64. }
  65. });
  66.  
  67. System.out.println("Sortati descrescator dupa nume");
  68. printStudents(students);
  69. }
  70. }
Add Comment
Please, Sign In to add comment