Вы можете использовать java Compartor
для сортировки, создав Movie
в качестве модели class
. Вы можете добиться этого, используя следующий код:
public static void readDataFromFile(String filePath) throws FileNotFoundException
{
List<Movie> movies = new ArrayList<Movie>();
File file = new File(filePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String txtLine = sc.nextLine();
//Extract data from single from txt file row
String[] data = txtLine.split(":");
Movie movie = new Movie(data[0], data[1], data[2], data[3], data[4]);
//Add to movies list
movies.add(movie);
}
System.out.println("Unsorted-----------");
System.out.println(movies);
System.out.println("Sorting by director-----------");
Collections.sort(movies, new DirectorSorter());
System.out.println(movies);
System.out.println("Sorting by producer-----------");
Collections.sort(movies, new ProducerSorter());
System.out.println(movies);
}
public static class Movie
{
private String name;
private String director;
private String producer;
private String rating;
private String review;
public Movie(){}
public Movie(String name, String director, String producer, String rating, String review){
this.name = name;
this.director = director;
this.producer = producer;
this.rating = rating;
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
@Override
public String toString() {
return "Movie : " + name + " - " + director + " - " + producer + " - " + rating + " - " + review + "\n";
}
}
public static class DirectorSorter implements Comparator<Movie>{
@Override
public int compare(Movie o1, Movie o2) {
return o1.getDirector().compareTo(o2.getDirector());
}
}
public static class ProducerSorter implements Comparator<Movie>{
@Override
public int compare(Movie o1, Movie o2) {
return o1.getProducer().compareTo(o2.getProducer());
}
}