【问题标题】:Sorting set of string numbers in java在java中对一组字符串数字进行排序
【发布时间】:2014-11-14 01:09:55
【问题描述】:

我需要对一组包含数字的字符串进行排序。Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8]。我需要将其排序为[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]。但是当我使用设置了keyList的Collections.sort(keyList);时,我得到的结果是[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]。请帮忙。

【问题讨论】:

  • 字符串比较是按字母顺序进行的。尝试将其转换为整数列表以获得所需的结果。
  • 请贴出您使用的实际代码。
  • Collections.sort 接受 Comparator 作为参数。这使您可以自己定义比较函数。 (实际上,修改为int,然后比较值)

标签: java sorting collections set


【解决方案1】:

编写一个自定义比较器并将其解析为Collections.sort(Collection,Comparator) 的参数。一种解决方案是将字符串解析为整数。

    Collections.sort(keyList, new Comparator<String>()
    {
        @Override
        public int compare(String s1, String s2)
        {
            Integer val1 = Integer.parseInt(s1);
            Integer val2 = Integer.parseInt(s2);
            return val1.compareTo(val2);
        }
    });

【讨论】:

    【解决方案2】:

    你可以试试:

    final int[] searchList =
            new int[] { 15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8 };
    Arrays.sort(searchList);
    

    结果是:

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    

    列表需要int

    【讨论】:

      【解决方案3】:

      您的字符串将按自然顺序而不是数字排序为字符串。所以,"11""10" 之后,"2" 将在"11111111110" 之后。

      怎么办?

      使用Integer.parseInt()将集合中的每个字符串值解析为整数,然后将它们添加到集合中并调用Collections.sort()

      【讨论】:

        【解决方案4】:

        先将Strings 转换成Integers。

        List<Integer> ints = new ArrayList<>();
        for (String s : strings)
            ints.add(Integer.parseInt(s));
        Collections.sort(ints);
        

        如果不需要重复值,可以使用SortedSet,它会自动维护顺序:

        SortedSet<Integer> ints = new TreeSet<>();
        for (String s : strings)
            ints.add(Integer.parseInt(s));
        // all done!
        

        【讨论】:

          【解决方案5】:

          你可以按照凯说的做,把你的字符串转换成整数并比较它

          但这是昂贵的操作,我建议是这样的:

           keyList.sort(new Comparator<String>() {
          
                  @Override
                  public int compare(String o1, String o2) {
                      if (o1.length() == o2.length()){
                          return o1.compareTo(o2);
                      }
                      return o1.length() - o2.length();
                  }
              });
          

          如果您的号码长度相同,则使用String.compareTo 进行比较,否则按顺序排序,因此 1 2 3 将自动排在 11 22 等之前

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-08-02
            • 2012-10-14
            • 2021-03-21
            • 1970-01-01
            • 2011-07-01
            • 2013-05-26
            相关资源
            最近更新 更多