|
| 1 | +package ObjectOrdering; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.Comparator; |
| 6 | + |
| 7 | + |
| 8 | +class MovieCom { |
| 9 | + private double rating; |
| 10 | + private String name; |
| 11 | + private int year; |
| 12 | + |
| 13 | + public MovieCom(String n, double rt, int y) { |
| 14 | + this.name = n; |
| 15 | + this.rating = rt; |
| 16 | + this.year = y; |
| 17 | + } |
| 18 | + |
| 19 | + public double getRating() { |
| 20 | + return rating; |
| 21 | + } |
| 22 | + |
| 23 | + public String getName() { |
| 24 | + return name; |
| 25 | + } |
| 26 | + |
| 27 | + public int getYear() { |
| 28 | + return year; |
| 29 | + } |
| 30 | + public String toString() { |
| 31 | + return "Name: "+name+"\tRating: "+rating+"\tYear: "+year; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class RatingCompare implements Comparator<MovieCom> { |
| 36 | + public int compare(MovieCom m1, MovieCom m2) { |
| 37 | + return (m1.getRating() < m2.getRating()) ? -1 : ((m1.getRating() > m2.getRating()) ? 1 : 0); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class NameCompare implements Comparator<MovieCom> { |
| 42 | + public int compare(MovieCom m1, MovieCom m2) { |
| 43 | + return m1.getName().compareTo(m2.getName()); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +public class ComparatorMovie { |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + ArrayList<MovieCom> mov = new ArrayList<>(); |
| 51 | + mov.add(new MovieCom("Inception ", 8.9, 2010)); |
| 52 | + mov.add(new MovieCom("The Dark Knight", 9.0, 2008)); |
| 53 | + mov.add(new MovieCom("Intersteller", 8.7, 2014)); |
| 54 | + mov.add(new MovieCom("The Prestige", 8.2, 2005)); |
| 55 | + System.out.println("Sorted Movie list on the basis of Name."); |
| 56 | + Collections.sort(mov,new NameCompare()); |
| 57 | + for(MovieCom m:mov) |
| 58 | + System.out.println(m); |
| 59 | + System.out.println("\nSorted Movie list on the basis of Rating."); |
| 60 | + Collections.sort(mov,new RatingCompare()); |
| 61 | + for(MovieCom m:mov) |
| 62 | + System.out.println(m); |
| 63 | + } |
| 64 | +} |
0 commit comments