java - Sorting a string of numbers with negative integers -
i have searched lot 2 days , not successful ,
now have strings 7 integer numbers ( both + , - ) separated comma .
i have written sample code explain .
arraylist<string> str = new arraylist<string>(); str.add("9,-9,21,23,28,29,35"); str.add("18,18,-21,28,28,32,34"); str.add("-11,-11,22,28,29,-30,31"); str.add("8,-8,26,31,31,31,31"); str.add("8,8,26,-32,25,29,35"); str.add("10,9,-21,45,25,29,35"); str.add("-11,59,21,25,25,-29,35"); str.add("12,-9,21,55,25,29,15"); str.add("9,9,21,25,25,-29,35"); str.add("7,9,21,25,-35,25,35"); str.add("4,-39,21,-15,25,-29,35"); str.add("9,9,21,25,27,29,-35"); str.add("10,9,21,35,25,39,15"); str.add("8,-9,21,-25,25,29,-35"); str.add("18,-9,21,-23,25,29,-35"); collections.sort(str);
this not return correct sorted array . tests first digit of numbers , proceed sorting .
but want , sorting must based on first numbers in string . if numbers same ( there 3 9 in first numbers of string arrays ), should check second numbers in those(tied strings alone) , sort accordingly , on .
the result should as
9 , -9 , 21 , 23 , 28 , 29 , 35 9 , 9 , 21 , 25 , 25 , -29 , 35 9 , 9 , 21 , 25 , 27 , 29 , -35
is there method sort in method . please let me know if , related answers welcomed .
thanks in advance .
use comparing method comparator sort(list list, comparator c):
collections.sort(str, new comparator<string>(){ public int compare(string str1, string str2){ int result = 0; int = 0; string [] s1 = str1.split(","); string [] s2 = str2.split(","); while ((i < s1.length) && (i < s2.length) && (result == 0)){ result = (integer.parseint(s1[i]) - integer.parseint(s2[i])); i++; } return (result); } });
Comments
Post a Comment