简体   繁体   中英

Sorting a String Array list by numeric order in Java (Beanshell)

I have following java code that I am using in beanshell Jmeter processor to create an ArrayList . In the end I need to sort contents of ArrayList in numeric order. Problem is that when I use collection.sort() , it gives output sorted by alphabetic order since it is String Arraylist . Can some one share the java/beanshell compatible code which can give me desired output sorted in numeric order. possibly a custom Comparator ?

NOTE: This code is to be executed in beanshell processor and that does not support latest java syntax and use of <> etc.

NOTE2: vars.put is JMeter built in method

// Input data is like below:
   student_id_RegEx_1=13
   student_id_RegEx_11=4
   student_id_RegEx_12=23
   student_id_RegEx_13=24

// CREATE ARRAY LIST AND STORE ELEMENTS IN IT
ArrayList strList = new ArrayList();
for (int i=0;i<25; i++){
strList.add(vars.get("student_id_RegEx_" + String.valueOf(i+1)));
}

// Print the ArrayList created by above method [output is]
vars.put("ArrayListBeforeSorting",strList);
ArrayListBeforeSorting=[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 4, 23, 24, 25, 26, 27, 28, 29, 5, 6, 7, 8, 9, 10, 11]


// Sort the ArrayList 
Collections.sort(strList);

//Print the sorted ArrayList [below is output]
vars.put("ArrayListAfterSorting",strList);
ArrayListAfterSorting=[10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 4, 5, 6, 7, 8, 9]

Expected output is sorted like this ... ** 4, 5, 6, 7, 8, 9, 10, 11..**

ArrayListBeforeSorting.get(i).split("x_");

Will split your string into the texts and then the numbers in this way:

    String[] x = ArrayListBeforeSorting.get(i).split("x_");
    int value = Integer.parseInt(x[1]); //this will be the numeric value

You can @Override the compare method if you make a class for your String you want to compare, and make it use the numeric value as a comparator like this

Make sure it extends comparable

@Override

public int compare(Object a1, Object a2) {
    int a = Integer.parseInt(a1.getValue().substring(17,a1.getValue().lenght-1); //Will parse the numbers, since they start at character 17 and they end at the end of the string
    int b = Integer.parseInt(a2.getValue().substring(17,a1.getValue().lenght-1);
    return a - b;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM