简体   繁体   中英

How do I sort an ArrayList include Date and String?

I want to sort my ArrayList by Date. My ArrayList as:

10 June - name
15 April - name
23 July - name
03 March - name

It has day, month and string name. How do I sort by Date?

Thanks

As pointed out by @The Elite Gentleman, you should use a custom comparator. Here's a complete example:

import java.text.*;
import java.util.*;
public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>(
                Arrays.asList("10 June - name", 
                              "15 April - name", 
                              "23 July - name", 
                              "03 March - name"));

        // Print list before sorting.
        System.out.println(list);

        // Sort list according to date.
        Collections.sort(list, new Comparator<String>() {
            DateFormat df = new SimpleDateFormat("dd MMM");
            @Override
            public int compare(String s1, String s2) {
                try {
                    Date d1 = df.parse(s1.split("-")[0].trim());
                    Date d2 = df.parse(s2.split("-")[0].trim());
                    return d1.compareTo(d2);
                } catch (ParseException pe) {
                    System.out.println("erro: " + pe);
                    return 0;
                }
            }
        });

        // Print list after sorting
        System.out.println(list);
    }
}

Output:

[10 June - name, 15 April - name, 23 July - name, 03 March - name]
[03 March - name, 15 April - name, 10 June - name, 23 July - name]

( A better idea may however be encapsulate the date/name pairs into a separate class. This would avoid the need to parse the string each time it needs to be used for these type of purposes.)

You can write your own date Comparator and pass sort it using Collections.sort(List<T>, Comparator<? super T> c); method.

Look at Comparator and Comparable .

In the Collections class there is a static method called sort(...) where you can pass a list and a comparator.

Create a comparator that compares the values from the list and return the appropriate value.

Here you an example:

List<Date> dates=new ArrayList<Date>();
dates.add(new Date(System.currentTimeMillis()));
dates.add(new Date(System.currentTimeMillis()+231892738));
dates.add(new Date(System.currentTimeMillis()-742367634));
for(Date d:dates)
    System.out.println(d);
Collections.sort(dates);
for(Date d:dates)
    System.out.println(d);

Or you can use custom comparator

Collections.sort(dates,customComparator);

Try using the Collections.sort method for your case:

Collections.sort(myList, new Comparator<String>(){

    @Override
    public int compare(String s1, String s2) {
          // perform the comparison here and returns a negative integer,
          // zero, or a positive integer as the first argument is less than,
          // equal to, or greater than the second 
    }
    });

create a function which turns that date string into an int? ie

str2int("name 10 June") => 610
str2int("name 15 Jan")  => 115

int str2int(String s){
    String[] elms = s.split("\\s+");
    // ignore first argument which is name
    int day = Integer.parseInt(elms[1]);
    int month = month2int(elms[2]);
    return day + month;
}

// month2int("Jan") => 100
// month2int("Feb") => 200
// .
// .
// month2int("Dec") => 1200

// you get the idea :-)

use a comparator which compares those Strings like that..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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