1

how to sort arraylist having elements like

02112-S1530   
02112-S1529  
02112-S1531 

in ascending order.

i am using Collection.sort(List name);
but getting output

02112-S1531  
02112-S1529   
02112-S1530  

Expected output is:

02112-S1529  
02112-S1530   
02112-S1531

i did like

List<String> gbosIdsList = new ArrayList<String>();
gbosIdsList.add("02112-S1530");
gbosIdsList.add("02112-S1529");
gbosIdsList.add("02112-S1531");
Collections.sort(gbosIdsList);
Iterator itr = gbosIdsList.iterator();
  while(itr.hasNext()){
      System.out.println(itr.next());           
}
user1912935
  • 361
  • 4
  • 13
  • 34

2 Answers2

1

I tried your code and got the output:

02112-S1529
02112-S1530
02112-S1531

Also, you have make your iterator generic

Generics 101: don't use Raw type in new code

Iterator<String> itr = gbosIdsList.iterator();
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • Please look here: http://stackoverflow.com/questions/11176227/simple-way-to-sort-strings-in-the-alphabetical-order – Michael Mar 19 '13 at 11:04
0

Define a comparator like this

public class MyComparator implements Comparator<String> {

    /* (non-Javadoc)
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    @Override
    public int compare(String arg0, String arg1) {
        //Do your processing here 
        //and
        //return +1 if arg0 > arg1
        //return 0 if arg0 == arg1
        //return -1 if arg0 < arg1
        return 0;
    }

}

Then add this to your sort

List<String> gbosIdsList = new ArrayList<String>();
//add values
Collections.sort(gbosIdsList,new  MyComparator());

FYR you can read this

Anubhab
  • 1,736
  • 2
  • 18
  • 28