I have a class, Library, that contains an array of Book objects, and I need to sort the array based off the properties of Book, either Title or PageNumber. The problem is im not allowed to use the Comparable class with Book. How would you recommend I sort the array of Books in library? Write my own sort? Or is there an easier way? If you need snippets of code, just ask!
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
Stick this in your Library:
Expanding @PeterLawrey's answer to Java 8, you can now use a Lambda Expression instead of a
Comparable<T>
delegate:You can provide a
Comparator
for comparing any type you wish,Comparable
or otherwise.For Arrays and Collections you use
Even sorted collections like TreeSet can take a custom Comparator
e.g.
create a new treeMap and switch the roles between key and value.
TreeMap<Title ,Book> treeMap = new TreeMap<Title,Book>();
Copy all the data to the new TreeMap.
You now have a sorted collection based on Title. (And no Comparator required :))
If you can use
Comparators
, write one for each type of sorting you need, e.g., ascending for book title and descending for page number. Thecompare
method of aComparator
must return positive if the first argument is larger than the second, negative if the first is smaller and zero if they are equal.