Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an ArrayList by its elements size in Java?

So I have a List<String> 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.

like image 888
miTzuliK Avatar asked May 11 '26 09:05

miTzuliK


1 Answers

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);
like image 113
curob Avatar answered May 13 '26 00:05

curob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!