Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort this ArrayList the way that I want?

Here is a simple sorting program of an ArrayList:

ArrayList<String> list = new ArrayList<String>();  list.add("1_Update"); list.add("11_Add"); list.add("12_Delete"); list.add("2_Create");  Collections.sort(list); for (String str : list) {   System.out.println(str.toString()); } 

I was expecting the output of this program as:

1_Update 2_Create 11_Add 12_Delete 

But when I run this program I am getting output as:

11_Add 12_Delete 1_Update 2_Create 

Why is this and how do I get the ArrayList to sort as shown in the expected output?

like image 413
B. S. Rawat Avatar asked May 20 '09 21:05

B. S. Rawat


People also ask

What is the best way to sort the elements of an ArrayList?

In order to sort elements in an ArrayList in Java, we use the Collections. sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order.

Does ArrayList have a sort method?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.


1 Answers

You could write a custom comparator:

Collections.sort(list, new Comparator<String>() {     public int compare(String a, String b) {         return Integer.signum(fixString(a) - fixString(b));     }     private int fixString(String in) {         return Integer.parseInt(in.substring(0, in.indexOf('_')));     } }); 
like image 167
nsayer Avatar answered Sep 21 '22 21:09

nsayer