我有创建 Books 对象或 Author 对象的地图的 Library 类,我需要能够使用 Book 对象属性对地图进行排序。该地图用于创建两个 JTable,一个用于书籍,另一个用于作者,我需要能够对书籍表中作为书籍属性的列进行排序。我必须使用地图,不能只使用 JTable 排序器顺便说一句。使用 bookIndex 作为键创建地图会为 bookIndex 正确排序地图,但这是自然顺序。
如何对已经由 Book 对象其他属性创建的地图进行排序。例如,如果我希望它根据 bookTitle 对现有地图进行排序?
我知道我需要使用比较器,但我已经搜索并尝试过,但无法弄清楚。
主要(创建图书馆对象并创建书籍和作者对象并将其添加到图书馆地图):
static Library<Book> bookLibrary = new Library<Book>();
Book book = new Book();
book.setBookIndex(Integer.parseInt(ar[1]));
book.setTitle(ar[2]);
book.setGenre(ar[3]);
book.setPrice(ar[4]);
book.setAuthorIndex(Integer.parseInt(ar[5]));
bookLibrary.add(book.getBookIndex(), book); //adds the book object to library
static Library<Author> authorLibrary = new Library<Author>();
Author author = new Author();
author.setAuthorIndex(Integer.parseInt(ar[1]));
author.setName(ar[2]);
author.setStreetAddress(ar[3]);
author.setCity(ar[4]);
author.setState(ar[5]);
author.setZip(ar[6]);
author.setPhone(ar[7]);
authorLibrary.add(author.getAuthorIndex(), author); //adds the author object to the library
书类(作者类与此类似):
public class Book implements BookInterface {
private Integer bookIndex;
private String title, genre, price;
private Integer authorIndex;
....
}
图书馆类:
public class Library<T> implements LibraryInterface<T> {
private Map<Integer, T> map = new TreeMap<Integer, T>();
...
}
. . .
为了将来参考,这里是我如何让它工作的:
public class Library<T> implements LibraryInterface<T> {
private Map<String, T> map = new TreeMap<String, T>(new bookComparator());
和新课程:
public class bookComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
String bookTitle1 = (String) o1;
String bookTitle2 = (String) o2;
int res = bookTitle1.compareToIgnoreCase(bookTitle2);;
return res != 0 ? res : 1;
}
}
并在主类中创建一个排序方法来创建一个新的 TreeMap。我会创建原始地图的副本并替换原始地图,但它现在可以使用:
/**
* Sort The Book Table by Book Title
*
* @param bookLibrary2
*/
private void sortByBookTitle() {
bookRowElement.clear();
Library<Book> sortBookLibrary = new Library<Book>();
for ( Entry<String, Book> entry: bookLibrary.entrySet()) {
String key = entry.getValue().getTitle(); //Additional sorts can be mad by changing .getTitle() to getWhatever()
Book value = entry.getValue();
sortBookLibrary.add(key, value);
}
for ( Entry<String, Book> entry: sortBookLibrary.entrySet()) {
bookRowElement.addElement(createBookSearchList(entry.getValue()));
}
bookTable.repaint();
}