java - 如何按字母顺序排序(没有 Comparable 或 Comparator 接口(interface))

标签 java sorting arraylist

我在练习 Java 时遇到了一个问题。

我有一个 Book 类,它存储以下信息:

id (int), author and title

我还有另一个类 BookShelf,它使用 Vector/ArrayList 存储书籍集合,并具有以下方法:

addBook: takes in a book object as input, adds the object into the bookshelf, method returns nothing.

returnListOfBooks: takes in no argument and returns a Vector/ArrayList of all books sorting by title in alphabetical order.

returnListOfBooksByAuthor: takes in author as input and returns a Vector/ArrayList of books by that author

我的问题是,如何创建方法returnListOfBooks 并按书名字母顺序对它们进行排序?如果您能检查我的方法并在我做错的时候纠正我,那就太好了。

我必须实现排序(冒泡排序、插入排序等)

我是 Java 的新手,所以我不太擅长它。任何帮助将不胜感激!

最佳答案

在 Java 中,您通常使用 Collections.sortList 进行排序,如果需要,还可以使用自定义比较器。 Java 8 允许使用简洁的语法。

// easy to change for descending order
Collections.sort(listOfBooks, (a, b) -> a.getTitle().compareTo(b.getTitle()));

甚至更好

Collections.sort(listOfBooks, Comparator.comparing(Book::getTitle));

请注意,两者都会对 listOfBooks 进行排序(而不是返回一个新的排序列表)。您可能不希望每次调用 returnListOfBooks 时都这样做。如果例如在 returnListOfBooksByAuthor 里面你可以

Collections.sort(listOfBooks, Comparator.comparing(Book::getAuthor));

相同的listOfBooks这次会按照author排序

关于java - 如何按字母顺序排序(没有 Comparable 或 Comparator 接口(interface)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546443/

相关文章:

java - 在替换之前如何对replaceAll中的正则表达式部分进行计算?

按索引对 haskell 中的元组数组进行排序

java - 数组:计数、比较和增加

java - 如何根据List<Object> java中的分数获取前7名

java - Gerrit 加载失败 "Starting Gerrit Code Review: FAILED"日志中没有错误

java - 权威的 Java Swing 入门指南和引用是什么?

java - 组织.hibernate.HibernateException : save is not valid without active transaction

javascript - 使用带有用户输入的 vanilla js 从 (poke) API 中对 API 数据进行排序

java - 选择排序不起作用

java - 如何在Java中拆分字符串并将其存储在不同的列表中