How to sort ArrayList<String> by the prefixed Integer value

Andi Sayid :

How to search sort arraylist which has a number value in front of it, the plan is I want to sort the listview with the largest to the smallest number

private void setupData(){
    ArrayList<String> hasil = new ArrayList<>();
    Set<String> keySet = chains.keySet();
    for(String key : keySet){
        float ms = Float.parseFloat(chains.get(key).get(0));
        float ma = 0;
        for(String str : chains.get(key)){
            if(str.contains(","))
                ma += Float.parseFloat(str.split(",")[1]);
        }

        float pa = ma * 100;
        String namaGangguan = SQLiteHelper.getInstance(this).getGangguan(key).getNama();
        hasil.add((int)pa + " % " + namaGangguan); // this is i want sorting
    }

    Collection.sort(hasil); //this is my code

    ArrayAdapter<String> diagnoseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hasil);
    listView.setAdapter(diagnoseAdapter);
}

How to search sort arraylist which has a number value in front of it, the plan is I want to sort the listview with the largest to the smallest number

ruhul :

As you need to sort it using the number in front of that string you need to provide a custom comparator Collections::sort : for example:

   Collections.sort(hasil, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            // null check needed?
            int diff = getIntValue(o2) - getIntValue(o1);
            if (diff == 0) return o1.compareTo(o2);
            return diff;
        }

        int getIntValue(String str) {
            if (str == null) return 0;
            int value = 0;
            int indx = 0;
            while (indx < str.length() && Character.isDigit(str.charAt(indx))) {
                value = value * 10 + (str.charAt(indx) - '0');
                indx++;
            }
            return value;
        }
    });



    System.out.println(hasil);

For input values:

List<String> list = new ArrayList<>();

    list.add("123 %kljadfd");
    list.add("1 %kljadfd");
    list.add("11123 %kljadfd");
    list.add("9 %kljadfd");

This will output:

   [ 11123 %kljadfd,
     123 %kljadfd,
     9 %kljadfd,
     1 %kljadfd ]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=154508&siteId=1