以两种不同的方式使用类进行字母排序。

huangapple go评论65阅读模式
英文:

Sorting alphabetically in 2 different ways using classes

问题

我有一个程序,其中我需要接收一系列的书籍,并让用户选择按照作者或标题进行字母顺序排序。我有一个包含作者和标题变量以及设置器和获取器的Book类。

我尝试过查看其他非常类似问题的线程,但修复方法仍然给我带来错误。我最近尝试的一个方法是使用Collections.sort(books, Comparator.comparing(Book::getTitle))。这给我带来了参数冲突的错误。我还尝试过在我的Book类中添加一个自定义的compareTo方法,但我似乎找不到一种同时适用于作者和标题的方法。

怎样是最佳解决方法?

英文:

I have a program where I have take an array of books and give the user the choice to sort alphabetically by author or title. I have a Book class with Author and Title variables, as well as setters and getters.

I have tried looking at other threads with very similar questions, but the fix still gives me errors. The one I recently tried was using Collections.sort(books, Comparator.comparing(Book:getTitle)). This gave me an error for conflicting arguments. I have also tried adding a custom compareTo method to my Book class, but I can't seem to find a way to use that for both Author and Title.

What is the best way to go about this?

答案1

得分: 1

你还可以在书籍对象本身中使用Comparator接口。代码如下所示。首先按作者排序,然后按标题排序。根据JavaDocs,compareTo的int结果需要遵循规范:

public class Book implements Comparable{
    private String author;
    private String title;

    public Book(String author, String title){
        this.author = author;
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public String getTitle() {
        return title;
    }


    @Override
    public int compareTo(Object o) {
        Book other = (Book) o;

        //Your compare code goes here
        int result = this.author.compareTo(other.author);
        if(result ==0){
            result = this.title.compareTo(other.title);
        }
        return result;  // 此处返回result
    }
}

当您想要使用不同的排序方式时,可以使用Comparator对象:

public class AuthorComparator implements Comparator<Book>{

    @Override
    public int compare(Book a, Book b) {
        return a.getAuthor().compareTo(b.getAuthor());
    }
}

public class TitleComparator implements Comparator<Book>{

    @Override
    public int compare(Book a, Book b) {
        return a.getTitle().compareTo(b.getTitle());
    }
}

使用Comparator类对书籍数组进行排序:

Book[] books = getBooksFromSomewhere();
Arrays.sort(books, new TitleComparator());

//现在通过作者重新排序
Arrays.sort(books, new AuthorComparator());

如果您有一个名为'books'的Book对象列表,可以使用流实现更简单且更灵活的方法来实现您想要的效果:

private void printBooksByTitle(List<Book> unsortedBooks) {
    List<Book> titleSortedBooks = unsortedBooks.stream()
            .sorted(Comparator.comparing(Book::getTitle))
            .collect(Collectors.toList());

    titleSortedBooks.forEach(System.out::println);
}

书籍数组版本(用于更新后的问题):

private Book[] sortBooksByTitle(Book[] books) {
    Book[] titleSortedBooks = Arrays.stream(books)
            .sorted(Comparator.comparing(Book::getTitle))
            .toArray(Book[]::new);
}
英文:

You can also use the Comparator Interface in the book object itself. This could look like follows. It sorts per author first, then per title. From the JavaDocs the compareTo int result needs to follow the spec:
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

public class Book implements Comparable{
    private String author;
    private String title;

    public Book(String author, String title){
        this.author = author;
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public String getTitle() {
        return title;
    }


    @Override
    public int compareTo(Object o) {
        Book other = (Book) o;

        //Your compare code goes here
        int result = this.author.compareTo(other.author);
        if(result ==0){
            result = this.title.compareTo(other.title);
        }
        return ;
    }
}

When you want to use different sorting you can use the Comparator object:

public class AuthorComparator implements Comparator&lt;Book&gt;{

    @Override
    public int compare(Book a, Book b) {
        return a.getAuthor().compareTo(b.getAuthor());
    }
}

public class TitleComparator implements Comparator&lt;Book&gt;{

    @Override
    public int compare(Book a, Book b) {
        return a.getTitle().compareTo(b.getTitle());
    }
}

Sorting Arrays of books using Comparator classes:

book[] books = getBooksFromSomewhere();
Arrays.sort(books, new TitleComparator());

//now resort by Author
Arrays.sort(books, new AuthorComparator());

If you have a list of Book Object named 'books' there's easier and more flexible ways into achieving what you want using streams:

private void printBooksByTitle(List&lt;Book&gt; unsortedBooks)
        List&lt;Book&gt; titleSortedBooks = unsortedBooks.stream()
			.sorted(Comparator.comparing(Book::getTitle))
			.collect(Collectors.toList());

        titleSortedBooks.forEach(System.out::println);
}

Version for Array of Books (for the updated question):

private Book[] sortBooksByTitle(Book[] books){
    Book[] titleSortedBooks = Arrays.stream(books)
			.sorted(Comparator.comparing(Book::getTitle))
			.collect(Collectors.toArray(Book[]::new););
}

huangapple
  • 本文由 发表于 2020年10月28日 01:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64560091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定