Reputation: 381
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());
}
Upvotes: 1
Views: 5751
Reputation: 1786
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
Upvotes: 0
Reputation: 46408
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();
Upvotes: 1