如何按字母顺序排序

如何按字母顺序排序

本文介绍了如何按字母顺序排序(没有 Comparable 或 Comparator 接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came across a problem while practising Java.

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

I have a class Book which stores the following information:

id (int)、作者和标题

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

and I have another class BookShelf which store a collection of books using a Vector/ArrayList and have the following methods:

addBook:以书本对象作为输入,将该对象添加到书架中,方法不返回任何内容.

returnListOfBooks:不接受任何参数并返回按标题按字母顺序排序的所有书籍的 Vector/ArrayList.

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

returnListOfBooksByAuthor:将作者作为输入并返回该作者的书籍的 Vector/ArrayList

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

我的问题是,如何创建方法 returnListOfBooks 并按标题按字母顺序对它们进行排序?如果你能检查我的方法并纠正我,如果我做错了,那也太好了.

My question is, how do I create the method returnListOfBooks and sort them by title in alphabetical order? It would also be great if you could check my methods and correct me if what i'm doing is wrong.

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

I have to implement the sorting (bubble sort, insertion sort, and such)

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

I'm new to java so i'm not quite good at it. Any help would be greatly appreciated!

推荐答案

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

In Java you typically sort a List with Collections.sort and if needed a custom comparator. Java 8 allows a concise syntax for that.

// 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 里面你做

Mind you that both will sort listOfBooks in place (instead of returning a new sorted list). You probably don't want to do that every time you call returnListOfBooks. If for e.g. inside returnListOfBooksByAuthor you do

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

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

The same listOfBooks will be sorted in place according to author this time

这篇关于如何按字母顺序排序(没有 Comparable 或 Comparator 接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:58