So I have a List<String> L1 = new ArrayList<>() with the following strings as elements:
How do I sort the list by its element's size so that in the final state L1 should be like this:
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<String> stringList = new ArrayList<String>();
// Fill the list
Comparator<String> stringLengthComparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return Integer.compare(o1.length(), o2.length());
}
};
Collections.sort(stringList, stringLengthComparator);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With