我怎么能说我想要的方式排序此ArrayList? [英] How can I sort this ArrayList the way that I want?

查看:131
本文介绍了我怎么能说我想要的方式排序此ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个ArrayList的一个简单的排序程序:

 的ArrayList<串GT;名单=新的ArrayList<串GT;();list.add(1_Update);
list.add(11_Add);
list.add(12_Delete);
list.add(2_Create);Collections.sort(名单);
对于(字符串str:名单){
  的System.out.println(str.toString());
}

我期待这个程序的输出为:

  1_Update
2_Create
11_Add
12_Delete

但是,当我运行这个程序,我得到的输出:

  11_Add
12_Delete
1_Update
2_Create

这是为什么?我如何才能在预期的排序输出如图所示的ArrayList <?/ p>

解决方案

您可以编写一个自定义的比较:

  Col​​lections.sort(名单,新的比较&LT;串GT;(){
    公众诠释比较(一个字符串,字符串二){
        返回Integer.signum(fixString(一) - fixString(B));
    }
    私人诠释fixString(字符串中){
        返回的Integer.parseInt(in.substring(0,in.indexOf(_)));
    }
});

Here is a simple sorting program of an ArrayList:

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

list.add("1_Update");
list.add("11_Add");
list.add("12_Delete");
list.add("2_Create");

Collections.sort(list);
for (String str : list) {
  System.out.println(str.toString());
}

I was expecting the output of this program as:

1_Update
2_Create
11_Add
12_Delete

But when I run this program I am getting output as:

11_Add
12_Delete
1_Update
2_Create

Why is this and how do I get the ArrayList to sort as shown in the expected output?

解决方案

You could write a custom comparator:

Collections.sort(list, new Comparator<String>() {
    public int compare(String a, String b) {
        return Integer.signum(fixString(a) - fixString(b));
    }
    private int fixString(String in) {
        return Integer.parseInt(in.substring(0, in.indexOf('_')));
    }
});

这篇关于我怎么能说我想要的方式排序此ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆