【问题标题】:Issue with Sort native method Java排序本机方法Java的问题
【发布时间】:2016-03-22 04:06:28
【问题描述】:

我正在尝试使用原生 sort 方法对元素进行排序。

代码:

List<String> list = new ArrayList();
Collections.sort(list);

输入 1:

Before order: 65 31 37 37 72 76 61 35 57 37
After order:  31 35 37 37 37 57 61 65 72 76
Expected:     Ok.

输入 2:

Before order: 45 186 185 55 51 51 22 78 64 26 49 21
After order:  185 186 21 22 26 45 49 51 51 55 64 78
Expected:     21 22 26 45 49 51 51 55 64 78 185 186

问题是在某些情况下方法排序错误,我该如何解决?

【问题讨论】:

  • 使用Comparator
  • 你能告诉我们你的预期结果和实际结果吗?

标签: java sorting collections


【解决方案1】:

你有一个List&lt;String&gt;,所以Collections.sort 按字典顺序排列String(s)。您可以使用List&lt;Integer&gt; 之类的

List<Integer> al = Arrays.asList(45, 186, 185, 55, 51, 51, 22, 78, 64, 26, 49, 21);
Collections.sort(al);
System.out.println(al);

但是,如果您必须使用String(s),那么您需要提供自定义的Comparator(因为默认的String 排序不是您想要的)。类似的,

List<String> al = Arrays.asList("45", "186", "185", "55", "51", "51", //
        "22", "78", "64", "26", "49", "21");
Collections.sort(al, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
    }
});
System.out.println(al);

哪个输出(和第一个例子一样)

[21, 22, 26, 45, 49, 51, 51, 55, 64, 78, 185, 186]

【讨论】:

  • 可能值得指出的是,在 Java 8 中你可以特别简洁地做到这一点:list.sort(Comparator.comparingInt(Integer::parseInt));
  • 谢谢。而且,是的,我必须将它用作字符串。很好的贡献@PaulBoddington。顺便说一句,当我编写 @ElliottFricsh 的代码时,Netbeans 向我展示了另一个使用 lambda 的选项:(String o1, String o2) -&gt; Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2)));。也只是为了贡献。
【解决方案2】:

您应该使用整数比较器。

List<Integer> list = new ArrayList();
Collections.sort(list);

List<String> list = Arrays.asList(new String[]{"45", "186", "185", "55", "51", "51", "22", "78", "64", "26", "49", "21"});
Comparator<String> cmp = (String o1, String o2) -> Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
Collections.sort(list,cmp);
System.out.println(list);

【讨论】:

    【解决方案3】:

    你应该排序

    1. 字符串的整数值

    那是

    Collections.sort(list,
        Comparator.comparing(Integer::parseInt));
    

    或排序

    1. 字符串长度
    2. 字符串本身

    那是

    Collections.sort(list,
        Comparator.comparing(String::length)
                  .thenComparing(Function.identity()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多