0

Can anyone suggest a way to arrange the following object arraylist in descending order?

List<Object> = {/ele1/*,/ele1/subele1/*,/ele2/subele2/*,/ele2/*,/ele3/subele2/*,/ele3/*}

I need the output as

{/ele1/*,/ele2/*,/ele3/*,/ele1/subele1/*,/ele2/subele2/*,/ele3/subele2/*}

Is this possible to achieve using element length?

Prabhu
  • 394
  • 1
  • 7
  • 23
  • See [this](http://stackoverflow.com/questions/104599/sort-on-a-string-that-may-contain-a-number) – SMA Dec 26 '14 at 12:08
  • You already did. Unless you want a way to arrange an arbitrary list according to the rule you used for this list, in which case you'll need to specify what that rule is (your example is not in descending order). – Scott Hunter Dec 26 '14 at 12:17
  • Sorry I just updated the question. I need ascending / descending order based on the element length. – Prabhu Dec 26 '14 at 13:00

1 Answers1

1

You need to provide a custom comparator for sorting of the items which uses the element length as the comparison, something like this:

public static void main(String[] args) throws Exception {
    List<String> items = Arrays.asList("/ele1/*", "/ele1/subele1/*" ,"/ele2/subele2/*", "/ele2/*");
    Collections.sort(items, new MinLengthComparator());
    System.out.println(items);
}

private static class MinLengthComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        return o1.length() - o2.length();
    }
}
tddmonkey
  • 20,798
  • 10
  • 58
  • 67