Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.stream.Collectors;
- class Book implements Comparable<Book>{
- private String title;
- private String category;
- private float price;
- public float getPrice() {
- return price;
- }
- public String getBookCategory() {
- return category;
- }
- Book(String title, String category, float price){
- this.title = title;
- this.category = category;
- this.price = price;
- }
- @Override
- public int compareTo( Book o) {
- if (this.title.toLowerCase().equals(o.title.toLowerCase() )){
- return Float.compare(this.price,o.price);
- }
- else{
- return this.title.toLowerCase().compareTo(o.title.toLowerCase());
- }
- }
- @Override
- public String toString() {
- return String.format("%s (%s) %.2f",title,category,price);
- }
- }
- class BookCollection{
- List<Book> bookCollection;
- public BookCollection() {
- bookCollection = new LinkedList<>();
- }
- public void addBook(Book book){
- bookCollection.add(book);
- }
- public void printByCategory(String category){
- List<Book> copyCollection = bookCollection.stream()
- .filter(x -> x.getBookCategory().equals(category))
- .sorted().collect(Collectors.toList());
- copyCollection.forEach(System.out::println);
- }
- public List<Book> getCheapestN(int n){
- Comparator<Book> comparator = Comparator.comparing(Book::getPrice);
- return bookCollection.stream()
- .sorted()
- .sorted(comparator)
- .limit(n)
- .collect(Collectors.toList());
- }
- }
- public class BooksTest {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = scanner.nextInt();
- scanner.nextLine();
- BookCollection booksCollection = new BookCollection();
- Set<String> categories = fillCollection(scanner, booksCollection);
- System.out.println("=== PRINT BY CATEGORY ===");
- for (String category : categories) {
- System.out.println("CATEGORY: " + category);
- booksCollection.printByCategory(category);
- }
- System.out.println("=== TOP N BY PRICE ===");
- print(booksCollection.getCheapestN(n));
- }
- static void print(List<Book> books) {
- for (Book book : books) {
- System.out.println(book);
- }
- }
- static TreeSet<String> fillCollection(Scanner scanner,
- BookCollection collection) {
- TreeSet<String> categories = new TreeSet<String>();
- while (scanner.hasNext()) {
- String line = scanner.nextLine();
- String[] parts = line.split(":");
- Book book = new Book(parts[0], parts[1], Float.parseFloat(parts[2]));
- collection.addBook(book);
- categories.add(parts[1]);
- }
- return categories;
- }
- }
- // Вашиот код овде
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement