gpt4 book ai didi

java - 如何先按字母顺序排序ArrayList,然后按数字排序

转载 作者:行者123 更新时间:2023-12-01 07:44:53 26 4
gpt4 key购买 nike

这是排序前的样子。书名、出版年份

enter image description here

我想按字母顺序对标题进行排序,然后按发布年份进行排序。
这是我当前在排序之前的编码:

    ArrayList BookList = new ArrayList();
BufferedReader br = new BufferedReader (new FileReader ("bookInput.txt"));

String str = br.readLine();
while (str!=null){
StringTokenizer st = new StringTokenizer(str,";");
String title = st.nextToken();
String yr = st.nextToken();
int year = Integer.parseInt(yr);
Book b1 = new Book (title,year);
BookList.add(b1);
str = br.readLine();
}
br.close();

//3(d)
System.out.println("List of Books" + "( " + BookList.size() + " record(s) ) ");
for (int i = 0; i < BookList.size(); i++){
Book b2 = (Book)BookList.get(i);
System.out.println("#" + (i+1) + " " + b2.getTitle() + " , " + b2.getYear());
}

我已经尝试了我所知道的一切,但失败了😅

最佳答案

您可以使用Comparator假设 Book 类具有 getters 的链:

BookList.sort(Comparator.comparing(Book::getTitle)
.thenComparingInt(Book::getYear));

关于java - 如何先按字母顺序排序ArrayList,然后按数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55298420/

26 4 0