Question

private ArrayList<String> mArrayList = new ArrayList<String>();

    mArrayList.clear();

    mArrayList.add("test 3");
    mArrayList.add("test 21");
    mArrayList.add("test 4");
    mArrayList.add("test 6");
    mArrayList.add("test 1");

    Collections.sort(mArrayList);

    for (int i = 0; i < mArrayList.size(); i++) {

        Log.e("TAG", "" + mArrayList.get(i));
    }

Result is:

test 1
test 21
test 3
test 4
test 6

But i want:

test 1
test 3
test 4
test 6
test 21

I sorted it but not perfectly, How to do that, i don't know, if you have any idea, than please share with me.

Was it helpful?

Solution

Although not a good solution but you will get an idea, Try this:

Collections.sort(mArrayList, new Comparator<String>() {
            public int compare(String s1, String s2) {
               Integer i1 = Integer.parseInt(s1.split("test ")[1]);
               Integer i2 = Integer.parseInt(s2.split("test ")[1]);
                return i1.compareTo(i2);
            });

Basically you can sort any object. So I recommend having a Data class containing all your variables then you can sort these objects on any variable's basis. So e.g.

public class Data{
    public String test;
    public Integer i;

}

ArrayList<Data> mArrayList = new ArrayList<Data>();
.
.
.


Collections.sort(mArrayList, new Comparator<Data>() {
            public int compare(Data d1, Data d2) { 
                return d1.i.compareTo(d2.i);
            });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top