• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 673
  • Last Modified:

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
0
coder-rl
Asked:
coder-rl
  • 3
1 Solution
 
Ajay-SinghCommented:
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now