How To Sort Arraylist Of String Having Integer Values In Java
I am having string list which consists of integer values. i just want to sort in ascending as well as in descending order. ArrayList a = new ArrayList(
Solution 1:
The better way will be to add integers/long in to the ArrayList and then sorting it using Collections.sort(a)
method.
If you still want to using String, you will need to make some modifications. Please find below code for the same:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
publicclassInputimplementsComparator<String>{
publicstaticvoidmain(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("1435536000000");
a.add("1435622400000");
a.add("1");
a.add("10");
a.add("20");
a.add("15");
a.add("1435622400010");
System.out.println("Before : " + a);
Collections.sort(a, new Input());
System.out.println("After : " + a);
}
publicintcompare(String lhs, String rhs) {
long i1 = Long.parseLong(lhs);
long i2 = Long.parseLong(rhs);
return (int) (i1-i2);
}
}
Solution 2:
Try using :
Collections.sort(a);
Without any Comparator. It will sort any String
alphabetically so logically it will serve for integer
String too.
Solution 3:
You can use this methods to sorting the Strings.
Collections.sort(arraylist);// for ascending order
Collections.sort(arraylist, Collections.reverseOrder());// for descending order.
Post a Comment for "How To Sort Arraylist Of String Having Integer Values In Java"