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?
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.
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.
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('_'))); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With