gpt4 book ai didi

java - 根据比较器使用字符串日期排序?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:54 25 4
gpt4 key购买 nike

我有以下类(class):

public class Book implements Cloneable {
private int ISBN;
private String title;
private String publishDate;
private int pageCount;
}

我可以使用以下代码根据 Comparator 进行排序:

Comparator<Book> titleComparator = new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.title.compareTo(o2.title);
}
};

Comparator<Book> ISBNComparator = new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return Integer.valueOf(o1.ISBN).compareTo(o2.ISBN);
}
};

public void sort(final String field, ArrayList<Book> BookList) {
final Comparator<Book> comparator;

if (field.equals("title")) {
comparator = titleComparator;
} else if (field.equals("ISBN")) {
comparator = ISBNComparator;
} else {
throw new IllegalArgumentException("Comparator not found for " + field);
}

Collections.sort(BookList, comparator);
}

但是当发布日期格式为“25/12/2015”时,如何根据字符串 publishDate 进行排序?

最佳答案

如果您确定不能选择使用 Date 而不是 String,请使用此比较器(您可以添加一些缓存以避免每次都解析字符串):

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;

/**
*
* @author EBudaqov
*/
public class StringDateComparator implements Comparator<String>{

private SimpleDateFormat formatter;

public StringDateComparator(String dateFormat) {
formatter = new SimpleDateFormat(dateFormat);
}

@Override
public int compare(String s1, String s2) {
try {
return formatter.parse(s1).compareTo(formatter.parse(s2));
} catch(ParseException exception) {
throw new RuntimeException(exception);
}
}

public static void main(String[] args) {
String s1 = "01/01/2015";
String s2 = "02/01/2015";

System.out.println(new StringDateComparator("dd/MM/yyyy").compare(s1, s2));
}

}

关于java - 根据比较器使用字符串日期排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com