Tasmin Tasmin - 1 year ago 71
Java Question

Sorting string array as per numeric value

I have a string array. This array is made of three integer array. But each of the Integer is followed by a character. Either l or p or r.
now my aim is to sort the string array according to int values. Array sort or

does not work properly. In my case if the array is
{-2l 1r 0p 4p 3l} the answer should be {-2l 0p 1r 3l 4p}.

String[] left = new String[starts.length];
String[] right = new String[ends.length];
String[] points_fast = new String[points.length];

for (int i = 0; i < starts.length; i++) {
left[i] = (starts[i] + "l" + " ");
for (int i = 0; i < ends.length; i++) {
right[i] = (ends[i] + "r" + " ");
for (int i = 0; i < points.length; i++) {
points_fast[i] = (points[i] + "p" + " ");
String[] add = new String[left.length + right.length + points_fast.length];
// add=l+r+p;
System.arraycopy(left, 0, add, 0, left.length);
System.arraycopy(right, 0, add, left.length, right.length);
System.arraycopy(points_fast, 0, add, left.length + right.length, points_fast.length);

my aim is to sort the array "add".
N.B I tried to convert it to list and then use collections.sort. It does not work.

Answer Source

I hope this satisfy your solution: you just need to use the Collection.sort and override the comparator

 List<String> mnames1 = Arrays.asList("-2l", "1r", "0p", "4p", "3l");
    System.out.println(mnames1+" before");
    Collections.sort(mnames1, new Comparator<String>() {
        public int compare(String a, String b) {
            String m = a.substring(0,a.length()-1);
            String n = b.substring(0,b.length()-1);
            return Integer.compare(Integer.parseInt(m),Integer.parseInt(n));
    System.out.println(mnames1+ "after");


[-2l, 1r, 0p, 4p, 3l] before

[-2l, 0p, 1r, 3l, 4p]after

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download