Skip to content
Advertisement

Sort ArrayList of strings by length

I want to order an ArrayList of strings by length, but not just in numeric order.

Say for example, the list contains these words:

JavaScript

They need to be ordered by their difference in length to a special string, for example:

JavaScript

So the final list would look like this (difference in brackets):

JavaScript

Advertisement

Answer

Use a custom comparator:

JavaScript

Then sort the list using java.util.Collections.sort(List, Comparator).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement