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.

Mr.Sandy
4,3494 gold badges33 silver badges54 bronze badges
asked Aug 15, 2013 at 13:36

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

answered Aug 15, 2013 at 13:38

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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.