简体   繁体   English

使用字符串日期对对象的Java列表进行排序

[英]Sorting Java List of objects using string date

I know there are lots of posts out there on sorting lists/arrays etc, but I'm a bit confused as to the best way of doing it. 我知道有很多关于排序列表/数组等的文章,但是对于最好的方法我有些困惑。 My list of objects also contains a date field - but that date is stored as a string, so do I need to convert them all first and then sort, or is there a way to sort the objects in the list using this parameter without first converting them? 我的对象列表还包含一个日期字段-但是该日期存储为字符串,所以我需要先将它们全部转换然后排序,还是有一种方法可以使用此参数对列表中的对象进行排序而无需先转换他们?

So basically the list: 所以基本上是列表:

List<NewsFeed> newslist;

The NewsFeed object: NewsFeed对象:

String title;
String description;
String URL;
String date;

Date looks something like: 日期看起来像:

Fri Dec 26 23:00:00 AEDT 2014

Use this 用这个

Collections.sort(newsList, new Comparator<NewsFeed>() {
        DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
        @Override
        public int compare(NewsFeed o1, NewsFeed o2) {
            try {
                return f.parse(o1.getDate()).compareTo(f.parse(o2.getDate()));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });

With Comparable it looks like this: 使用Comparable它看起来像这样:

   public class NewsFeed implements Comparable<NewsFeed>{
        //your fields and getters/setters
        private DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
        @Override
        public int compareTo(NewsFeed o) {
            try {
                return f.parse(this.getDate()).compareTo(f.parse(o.getDate()));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
       }
}

Your class NewsFeed have to implement Comparable interface and @override compareTo method to define your sort rule. 您的类NewsFeed必须实现Comparable接口和@override compareTo方法来定义您的排序规则。 Then use Arrays.sort method to sort your newslist . 然后使用Arrays.sort方法对newslist进行排序。

class NewsFeed implements Comparable<NewsFeed>{
    //members
    @Override
    public int compareTo(NewsFeed o) {
        // TODO Your sort rule
        return 0;
    }

}

List<NewsFeed> newslist;
...
Arrays.sort(newslist);

Convert the string to a date as you read the RSS, and store it as a Date in your NewsFeed object. 阅读RSS时,将字符串转换为日期,并将其作为Date存储在NewsFeed对象中。 Then you can implement the Comparable interface and delegate to the date. 然后,您可以实现Comparable接口并将其委托给日期。

Any answer that has you converting the date I'm the compareTo method will be doing an unnecessarily large number of conversions. 任何将您转换为compareTo方法的日期的答案都将进行不必要的大量转换。

If you can't just store the dates as Date objects, you need to define a custom comparator (that will end up implicitly converting the Strings to Date objects, so you really may as well just store them as dates). 如果不能仅将日期存储为Date对象,则需要定义一个自定义比较器(最终会将字符串隐式转换为Date对象,因此您也可以将它们存储为日期)。 You can define both of these as fields in your class: 您可以将这两个都定义为类中的字段:

private final static String dateFormat = "EEE MMM dd HH:mm:ss yyyy";
private final static Comparator<String> dateComp = new Comparator<String>() {
        public int compare(String s1, String s2) {
            Date d1 = null;
            try {
                d1 = new SimpleDateFormat( dateFormat,Locale.ENGLISH ).parse(s1);
            } catch (ParseException e) {
                //HANDLE THIS EXCEPTION
            }

            Date d2 = null;
            try {
                d2 = new SimpleDateFormat( dateFormat,Locale.ENGLISH ).parse(s2);
            } catch (ParseException e) {
                //HANDLE THIS EXCEPTION
            }
            return d1.compareTo(d2);
        }
    };

Of course, you will have to effectively handle the required try/catch blocks and potential parsing exceptions. 当然,您将必须有效地处理所需的try / catch块和潜在的解析异常。 Additionally, you will have be to certain that is the format of your incoming date strings. 此外,您必须确定输入日期字符串的格式。

Here is an example using the above comparator: 这是使用上述比较器的示例:

    String[] dateArray = new String[] {"Sat Dec 27 23:00:00 2014","Fri Dec 26 23:00:00 2014","Sun Dec 28 23:00:00 2014"};
    List<String> dateList = new ArrayList<String>(Arrays.asList(dateArray));
    Collections.sort(dateList, dateComp);

Prints: 打印:

[Fri Dec 26 23:00:00 2014, Sat Dec 27 23:00:00 2014, Sun Dec 28 23:00:00 2014]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM