1

I have an arraylist with the following string.

Tuesday, Thursday, Monday, Saturday.

And I want to appear sorted like:

Monday, Tuesday, Thursday, Saturday.

It is possible that appears Sunday, Wednesday..

And I have an arraylist with the following String.

dog, rabbit, cow, duck, cat.

And I want to appear sorted like:

rabbit, cat, cow, duck, dog.

Is it possible? Thank you.

1 Answer 1

7

Yes, you should make a Comparator for each. Docs

public final class MyComparator implements Comparator<String>
{
    @Override
    public int compare(String a, String b)
    {
        //Return +1 if a>b, -1 if a<b, 0 if equal
    }
}

For your days of the week you might want to make your comparator similar to this;

public final class MyComparator implements Comparator<String>
{
    private String[] items ={
        "monday",
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
        "sunday"
    };
    @Override
    public int compare(String a, String b)
    {
        int ai = items.length, bi=items.length;
        for(int i = 0; i<items.length; i++)
        {
            if(items[i].equalsIgnoreCase(a))
                ai=i;
            if(items[i].equalsIgnoreCase(b))
                bi=i;
        }
        return ai-bi;
    }
}

Then to sort your arraylist according to your custom order;

MyComparator myComparator = new MyComparator();
Collections.sort(myArrayList, myComparator);

You can call Collections.sort() without the 2nd parameter if you need the default ordering of the type (If it implements comparable). Docs

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

14 Comments

You define the comparison whether a is less than b, inside the compare method. I've provided an example of one of the possible implementations to do this.
Updated, now the answer should make more sense to @JuanA.Doval
Yeah, i removed the additional comment part, easy mistakes when writing code without compiling/running. Thanks
@JuanA.Doval Your title says sorting of android date? If your formatting strings from date objects, you would be best to sort the list of dates using default comparator. And then produce the strings from the sorted list.
@JuanA.Doval It's quite possible that accent's cause the equality to screwup, would have to find a different equality check if that turns out to be true. I don't understand your word valorate.
|

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.