So I have a List L1 = new ArrayList<>() with the following strings as elements:
l, l, u, u.
r, u, d, l, d, l, u.
l, u, d, r, r, r, r, r, u, d.
l, u.
l, u, r.
How do I sort the list by its element's size so that in the final state L1 should be like this:
l, u.
l, u, r.
l, l, u, u.
r, u, d, l, d, l, u.
l, u, d, r, r, r, r, r, u, d.
I have tried using Collections.sort, but that sorts alphabetically, which is obviously not what I want.
解决方案
I think what you are looking for is Collections.sort(java.util.List, java.util.Comparator). With it you can specify a custom Comparator that compares the strings based on length instead of alphabetical relationship.
Something like this:
List stringList = new ArrayList();
// Fill the list
Comparator stringLengthComparator = new Comparator()
{
@Override
public int compare(String o1, String o2)
{
return Integer.compare(o1.length(), o2.length());
}
};
Collections.sort(stringList, stringLengthComparator);