android - how to sort Arraylist of string having integer values in java -
i having string list consists of integer values. want sort in ascending in descending order.
arraylist<string> = new arraylist<string>(); a.add("1435536000000"); a.add("1435622400000"); system.out.println("before : " + a); collections.sort(a, new comparatorofnumericstring()); system.out.println("after : " + a);
my comparatorofnumericstring class -
public class comparatorofnumericstring implements comparator<string> { @suppresslint("newapi") @override public int compare(string lhs, string rhs) { int i1 = integer.parseint(lhs); int i2 = integer.parseint(rhs); return integer.compare(i1, i2); } }
any 1 having idea how sort strings having integer values in java?
thanks lot!! in advance!!
the better way add integers/long in arraylist , sorting using collections.sort(a)
method.
if still want using string, need make modifications. please find below code same:
import java.util.arraylist; import java.util.collections; import java.util.comparator; public class input implements comparator<string>{ public static void main(string[] args) { arraylist<string> = 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); } public int compare(string lhs, string rhs) { long i1 = long.parselong(lhs); long i2 = long.parselong(rhs); return (int) (i1-i2); } }
Comments
Post a Comment