【问题标题】:How to sort ArrayList<String> by the prefixed Integer value [duplicate]如何按前缀整数值对 ArrayList<String> 进行排序[重复]
【发布时间】:2019-12-04 08:39:15
【问题描述】:

如何搜索前面有数字值的排序数组列表,计划是我想对数字最大到最小的列表视图进行排序

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);
}

如何搜索前面有数字值的排序数组列表,计划是我想对数字最大到最小的列表视图进行排序

【问题讨论】:

    标签: java android-studio


    【解决方案1】:

    由于您需要使用该字符串前面的数字对其进行排序,因此您需要提供自定义比较器Collections::sort:例如:

       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);
    

    对于输入值:

    List<String> list = new ArrayList<>();
    
        list.add("123 %kljadfd");
        list.add("1 %kljadfd");
        list.add("11123 %kljadfd");
        list.add("9 %kljadfd");
    

    这将输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2016-08-28
      • 2013-06-22
      • 2019-09-18
      • 1970-01-01
      • 2016-06-22
      相关资源
      最近更新 更多