简体   繁体   中英

Sorting objects alphabetically using a comparator?

I'm trying to sort an array of book objects alphabetically by title using Collections.sort , when I run this, it doesn't seem to give me any way to output the data.

public static void SortBooks(Scanner sc, ArrayList<Book> books) {
    Collections.sort(books, new Comparator<Book>() {
        public int compare(Book q1, Book q2) {
            return q1.getBookTitle().compareToIgnoreCase(q2.getBookTitle());
        } 
    });
}

Would anybody have a clue on how I could output this data to the console using System.out.println() ?

For completeness:

public static void SortBooks(Scanner sc, ArrayList<Book> books) {
    Collections.sort(books, new Comparator<Book>() {
        public int compare(Book q1, Book q2) {
            // don't put it in here
            return q1.getBookTitle().compareToIgnoreCase(q2.getBookTitle());
        } 
    });
    // put it here, after the sort
    System.out.println(books);
}

You can, of course, produce fancier output by iterating over books and printing each member in some particular way.

for ( Book b : books ) {
    System.out.println("Book: " + b.getBookTitle());
}

or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM