2

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

2
  • 1
    is your array list ArrayList<String>? is "10 June - name" one object? or is it splitted to 2/3/? objects? Commented Jun 30, 2011 at 11:12
  • yes "10 June -name" one object. Commented Jun 30, 2011 at 11:44

7 Answers 7

6

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Hah, you think? I try to never solve homework assignments at SO, so I hope this wasn't homework :P
No problem. You're welcome. Be sure to upvote all answers that you found helpful and accept (by clicking on the checkmark) the answer that solved your problem.
4

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

1 Comment

+1, This is the way to go. See my answer for a complete example.
1

Look at Comparator and Comparable.

1 Comment

Given his data is represented as strings, I can't see how Comparable would help him here.
0

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.

Comments

0

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);

Comments

0

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 
    }
    });

Comments

0

create a function which turns that date string into an int? i.e.

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.