如何通过字母顺序进行排序(不相当或比较器接口) [英] How to sort by alphabetical order (without Comparable or Comparator interfaces)

查看:266
本文介绍了如何通过字母顺序进行排序(不相当或比较器接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到一个问题就来了,练的Java。

I came across a problem while practising Java.

我有一个类的图书的存储下列信息:

I have a class Book which stores the following information:

ID(INT),作者和标题

id (int), author and title

和我有另一个类的书架其中存储的使用Vector / ArrayList的藏书,并有以下几种方法的:

addBook:发生在一本书对象作为输入,并将该对象添​​加到书架,方法不返回任何

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

returnListOfBooks:发生在没有参数和返回的所有书籍按标题的字母顺序排序的Vector / ArrayList的

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

returnListOfBooksByAuthor:发生在笔者作为输入,并通过该作者返回书籍的矢量/的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所以我不认为很好。任何帮助将大大AP preciated!

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

推荐答案

在Java中,你通常一个排序列表 Col​​lections.sort ,如果需要自定义比较。 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 作者将在地方进行排序此时

这篇关于如何通过字母顺序进行排序(不相当或比较器接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆