0

Possible Duplicate:
Sort ArrayList of custom Objects by property

I have an arrayList of String which contains following strings

Common Ruby Errors 45min
Rails for Python Developers lightning
Communicating Over Distance 60min
Accounting-Driven Development 45min
Woah 30min
Sit Down and Write 30min

Now I want to sort the arraylist in descending order according to the number mentioned in each string

i.e. sorted list should look like

Communicating Over Distance 60min
Common Ruby Errors 45min
Accounting-Driven Development 45min
Woah 30min
Sit Down and Write 30min
Rails for Python Developers lightning

Can anyone tell how can I do it?

Community
  • 1
  • 1
Pratik
  • 1,531
  • 3
  • 25
  • 57
  • I tried it using simple for loop. what i did is, first I split the integers from string and put them in new list then sort that list of numbers and again using for loop check for string which contains the numbers from sorted number list. its working.. But I want to use comparator – Pratik Oct 10 '12 at 07:27
  • 1
    Go through [Collections](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html) doc.. Specially: - http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator) – Rohit Jain Oct 10 '12 at 07:27

2 Answers2

3

As @Rohit suggests, your task is twofold

  • figure out how to extract the property you wish to sort on (the number)
  • write a Comparator that uses the method above and perform a sortedList = Collections.sort( list , new YourComparator() )

Something like this might be workable:

    Comparator c = new Comparator<String>()
    {
        @Override
        public int compare( String o1, String o2 )
        {
            return getNumber( o1 ).compareTo( getNumber( o2 ) );
        }

        private Integer getNumber( String str ) 
        {
            Pattern pattern = Pattern.compile("([0-9]+)");
            Matcher matcher = pattern.matcher(str);
            while ( matcher.find() ) { return Integer.parseInt( matcher.group( 1 ) ); }

            return 0;
        }
    }

Cheers,

Pratik
  • 1,531
  • 3
  • 25
  • 57
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1
  1. You must be able to extract the number from the strig. Regex will help
  2. You must be able to compare the numbers. Comparator will help

If you have those you just need to call

Collections.sort(yourLIstWithString, new YourNumberInStringComparator());