[英]TreeMap<String,(new TreeMap<String,Integer>()) Treemap With Object
[英]Sort TreeMap<Integer, Object> on object's attributes
我有一个Library类,该类创建Book对象或Author对象的地图,并且我需要能够使用Book对象属性对地图进行排序。 该地图用于创建两个JTable,一个用于书籍,另一个用于作者,我需要能够对作为书籍表中书籍属性的列进行排序。 我必须使用地图,不能只使用JTable排序器。 使用bookIndex作为键来创建地图会正确地为bookIndex排序地图,但这是自然的顺序。
如何对Book对象其他属性已经创建的地图进行排序。 例如,如果我希望它根据bookTitle对现有地图进行排序?
我知道我需要使用比较器,但是我已经搜索并尝试过了,无法解决。
Main(创建库对象,并将书籍和作者对象创建并添加到库地图):
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();
}
在您的情况下,我只是使用给定的比较器创建新的TreeMap并将所有元素复制到新地图。 我想你会得到你的结果
TreeMap有一个构造函数,您可以在其中传递自定义的Comparator 。 我想那将为您完成工作。
public TreeMap(Comparator<? super K> comparator)
您可以像这样上课:
public class Library<T> implements LibraryInterface<T> {
private Map<Integer, T> map = new TreeMap<Integer, T>(myComparator);
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.