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
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
14 Comments
a
is less than b
, inside the compare
method. I've provided an example of one of the possible implementations to do this.