Files
Assignment-5/src/main/java/Parser.java
T
2026-05-23 23:00:17 +03:30

69 lines
2.1 KiB
Java

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Parser {
private List<Movie> movies = new ArrayList<>();
public Parser(String filePath) throws IOException {
setUp(filePath);
}
public List<Movie> sortByTitle() {
List<Movie> sortedByTitle = new ArrayList<>(movies);
sortedByTitle.sort(Comparator.comparing(Movie::getTitle));
return sortedByTitle;
}
public List<Movie> sortByRating() {
List<Movie> sortedByRating = new ArrayList<>(movies);
sortedByRating.sort(Comparator.comparingDouble(Movie::getRating).reversed());
return sortedByRating;
}
public List<Movie> sortByYear() {
List<Movie> sortedByYear = new ArrayList<>(movies);
sortedByYear.sort(Comparator.comparingInt(Movie::getYear).reversed());
return sortedByYear;
}
private void setUp(String filePath) throws IOException {
File file = new File(filePath);
Document document = Jsoup.parse(file, "UTF-8");
Elements movieElements = document.select(".movie");
for (Element movieElement : movieElements) {
Element titleElement = movieElement.selectFirst("h3.movie-title");
String title = "Unknown Title";
if ((titleElement != null)) {
title = titleElement.text();
}
Element ratingElement = movieElement.selectFirst("span.movie-rating");
double rating = 0.0;
if (ratingElement != null) {
String ratingText = ratingElement.text().replace("/10", "").trim();
rating = Double.parseDouble(ratingText);
}
Element yearElement = movieElement.selectFirst("span.movie-year");
int year = 0;
if (yearElement != null) {
String yearText = yearElement.text().trim();
year = Integer.parseInt(yearText);
}
movies.add(new Movie(title, rating, year));
}
}
}