How to sort a arraylist<string> by the string length of the entries?

The list has these entries:

engine
engine oil
engine cylinder
engine belt
engine valve
car
car light
car doors

in any order.

How to sort them into a list with the longest string the first element in the list?

Thanks,

coder-rl
coder-rlAsked:
Who is Participating?
 
Ajay-SinghConnect With a Mentor Commented:
Use,

    Collections.sort(list, new Comparator() {

      @Override
      public int compare(String o1, String o2) {
        return Integer.valueOf(o2.length()).compareTo(o1.length());
      }
    });


Here list is the List. You need to import java.util.Collections
as well.
0
 
coder-rlAuthor Commented:
Hi Alex,

How to resume the original collection.sort behavor?

Thanks for showing how to instruct Java to use different predicate!

0
 
coder-rlAuthor Commented:
Hi Alex,

I undertood it now and it works for me.

It is actually a good example for me on overriding a function.

Thanks,

Robert
0
 
coder-rlAuthor Commented:
Hi Alex,

I undertood it now and it works for me.

It is actually a good example for me on overriding a function.

Thanks,

Robert
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.