我有一个 Library 类,它创建 Books 对象或 Author 对象的映射,并且我需要能够使用 Book 对象属性对映射进行排序。该 map 用于创建两个 JTable,一个用于书籍,另一个用于作者,我需要能够对书籍表中的书籍属性列进行排序。我必须使用 map ,不能只使用 JTable 排序器顺便说一句。使用 bookIndex 作为键创建 map ,可以根据 bookIndex 对 map 进行正确排序,但这是自然顺序。
如何对已由 Book 对象其他属性创建的 map 进行排序。例如,如果我希望它根据 bookTitle 对现有 map 进行排序?
我知道我需要使用比较器,但我已经搜索并尝试过,但无法弄清楚这一点。
主要(创建图书馆对象并创建书籍和作者对象并将其添加到图书馆 map ):
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());
新类(class):
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。我会创建原始 map 的副本并替换原始 map ,但它现在可以使用:
/**
* 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();
}
最佳答案
TreeMap has a constructor where you can pass in your custom Comparator 。我想这会为你完成这项工作。
public TreeMap(Comparator<? super K> comparator)
你可以像这样上课:
public class Library<T> implements LibraryInterface<T> {
private Map<Integer, T> map = new TreeMap<Integer, T>(myComparator);
// ...
}
关于java - 根据对象的属性对 TreeMap<Integer, Object> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16017597/